Semaphore.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "api.h"
  2. #include "pal.h"
  3. #include "pal_debug.h"
  4. void helper_timeout(PAL_NUM timeout) {
  5. /* Create a binary semaphore */
  6. PAL_HANDLE sem1 = DkMutexCreate(1);
  7. if (!sem1) {
  8. pal_printf("Failed to create a binary semaphore\n");
  9. return;
  10. }
  11. /* Wait on the binary semaphore with a timeout */
  12. PAL_HANDLE rv = DkObjectsWaitAny(1, &sem1, timeout);
  13. if (rv == NULL)
  14. pal_printf("Locked binary semaphore timed out (%ld).\n", timeout);
  15. else
  16. pal_printf("Acquired locked binary semaphore!?! Got back %p; sem1 is %p (%ld)\n", rv, sem1,
  17. timeout);
  18. DkObjectClose(sem1);
  19. }
  20. void helper_success(PAL_NUM timeout) {
  21. /* Create a binary semaphore */
  22. PAL_HANDLE sem1 = DkMutexCreate(0);
  23. if (!sem1) {
  24. pal_printf("Failed to create a binary semaphore\n");
  25. return;
  26. }
  27. /* Wait on the binary semaphore with a timeout */
  28. PAL_HANDLE rv = DkObjectsWaitAny(1, &sem1, timeout);
  29. if (rv == sem1)
  30. pal_printf("Locked binary semaphore successfully (%ld).\n", timeout);
  31. else
  32. pal_printf("Failed to lock binary semaphore: Got back %p; sem1 is %p\n", rv, sem1);
  33. DkObjectClose(sem1);
  34. }
  35. int main(int argc, char** argv, char** envp) {
  36. helper_timeout(1000);
  37. /* Try again with timeout 0 (trylock) */
  38. helper_timeout(0);
  39. /* Try cases that should succeed */
  40. helper_success(NO_TIMEOUT);
  41. helper_success(0);
  42. return 0;
  43. }