/synch/semaphore.d

http://github.com/wilkie/djehuty · D · 58 lines · 33 code · 14 blank · 11 comment · 1 complexity · d539934510f8c6368b74b71072f0a033 MD5 · raw file

  1. module synch.semaphore;
  2. import scaffold.thread;
  3. import platform.vars.semaphore;
  4. import core.definitions;
  5. // Section: Core/Synchronization
  6. // Description: This class abstracts a counting semaphore.
  7. class Semaphore {
  8. ~this() {
  9. if (_inited)
  10. {
  11. SemaphoreUninit(_pfvars);
  12. }
  13. }
  14. // Description: Creates an uninitialized semaphore.
  15. this() {
  16. }
  17. // Description: Creates and initializes a semaphore.
  18. // initialValue: The initial count for the semaphore.
  19. this(uint initialValue) {
  20. init(initialValue);
  21. }
  22. // Description: This function will initialize a semaphore and set it to an initial count.
  23. // initialValue: The initial count for the semaphore.
  24. void init(uint initialValue) {
  25. SemaphoreInit(_pfvars, initialValue);
  26. _inited = true;
  27. }
  28. // Description: This function will increment the count of the semaphore.
  29. void up() {
  30. SemaphoreUp(_pfvars);
  31. }
  32. // Description: This function will decrement the count of the semaphore as long as the count is greater than 0. If not, it will yield the thread until the count is incremented via an up() call. This is the blocking call of the semaphore.
  33. void down() {
  34. SemaphoreDown(_pfvars);
  35. }
  36. // Description: This function will decrement the count of the semaphore as long as the count is greater than 0. If not, it will yield the thread until the count is incremented via an up() call. This is the blocking call of the semaphore, but it will only block for as long as it is specified and will continue once there is a timeout.
  37. // milliseconds: The amount of time to block before continuing if the semaphore should have a count of zero.
  38. void down(uint milliseconds) {
  39. SemaphoreDown(_pfvars, milliseconds);
  40. }
  41. protected:
  42. SemaphorePlatformVars _pfvars;
  43. bool _inited = false;
  44. }