Semaphore.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include "pal.h"
  4. #include "pal_debug.h"
  5. #include "api.h"
  6. void helper_timeout(PAL_NUM timeout) {
  7. /* Create a binary semaphore */
  8. PAL_HANDLE sem1 = DkMutexCreate(1);
  9. if(!sem1) {
  10. pal_printf("Failed to create a binary semaphore\n");
  11. return;
  12. }
  13. /* Wait on the binary semaphore with a timeout */
  14. PAL_HANDLE rv = DkObjectsWaitAny(1, &sem1, timeout);
  15. if (rv == NULL)
  16. pal_printf("Locked binary semaphore timed out (%d).\n", timeout);
  17. else
  18. pal_printf("Acquired locked binary semaphore!?! Got back %p; sem1 is %p (%d)\n", rv, sem1, timeout);
  19. DkObjectClose(sem1);
  20. }
  21. void helper_success(PAL_NUM timeout) {
  22. /* Create a binary semaphore */
  23. PAL_HANDLE sem1 = DkMutexCreate(0);
  24. if(!sem1) {
  25. pal_printf("Failed to create a binary semaphore\n");
  26. return;
  27. }
  28. /* Wait on the binary semaphore with a timeout */
  29. PAL_HANDLE rv = DkObjectsWaitAny(1, &sem1, timeout);
  30. if (rv == sem1)
  31. pal_printf("Locked binary semaphore successfully (%d).\n", timeout);
  32. else
  33. pal_printf("Failed to lock binary semaphore: Got back %p; sem1 is %p\n", rv, sem1);
  34. DkObjectClose(sem1);
  35. }
  36. int main (int argc, char ** argv, char ** envp)
  37. {
  38. helper_timeout(1000);
  39. /* Try again with timeout 0 (trylock) */
  40. helper_timeout(0);
  41. /* Try cases that should succeed */
  42. helper_success(NO_TIMEOUT);
  43. helper_success(0);
  44. return 0;
  45. }