BinarySemaphore.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #pragma once
  2. #include "CappedSemaphore.h"
  3. namespace baselib
  4. {
  5. BASELIB_CPP_INTERFACE
  6. {
  7. // In computer science, a semaphore is a variable or abstract data type used to control access to a common resource by multiple processes in a concurrent
  8. // system such as a multitasking operating system. A semaphore is simply a variable. This variable is used to solve critical section problems and to achieve
  9. // process synchronization in the multi processing environment. A trivial semaphore is a plain variable that is changed (for example, incremented or
  10. // decremented, or toggled) depending on programmer-defined conditions.
  11. //
  12. // A useful way to think of a semaphore as used in the real-world system is as a record of how many units of a particular resource are available, coupled with
  13. // operations to adjust that record safely (i.e. to avoid race conditions) as units are required or become free, and, if necessary, wait until a unit of the
  14. // resource becomes available.
  15. //
  16. // "Semaphore (programming)", Wikipedia: The Free Encyclopedia
  17. // https://en.wikipedia.org/w/index.php?title=Semaphore_(programming)&oldid=872408126
  18. //
  19. // For optimal performance, baselib::BinarySemaphore should be stored at a cache aligned memory location.
  20. class BinarySemaphore : private CappedSemaphore
  21. {
  22. public:
  23. // Creates a binary semaphore synchronization primitive.
  24. // Binary means the semaphore can at any given time have at most one token available for consummation.
  25. //
  26. // This is just an API facade for CappedSemaphore(1)
  27. //
  28. // If there are not enough system resources to create a semaphore, process abort is triggered.
  29. BinarySemaphore() : CappedSemaphore(1) {}
  30. using CappedSemaphore::Acquire;
  31. using CappedSemaphore::TryAcquire;
  32. using CappedSemaphore::TryTimedAcquire;
  33. // Submit token to the semaphore.
  34. // If threads are waiting the token is consumed before this function return.
  35. //
  36. // When successful this function is guaranteed to emit a release barrier.
  37. //
  38. // \returns true if a token was submitted, false otherwise (meaning the BinarySemaphore already has a token)
  39. inline bool Release()
  40. {
  41. return CappedSemaphore::Release(1) == 1;
  42. }
  43. };
  44. }
  45. }