Semaphore.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2016 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #ifdef _WIN32
  5. #include <Windows.h>
  6. namespace Common
  7. {
  8. class Semaphore
  9. {
  10. public:
  11. Semaphore(int initial_count, int maximum_count)
  12. {
  13. m_handle = CreateSemaphoreA(nullptr, initial_count, maximum_count, nullptr);
  14. }
  15. ~Semaphore() { CloseHandle(m_handle); }
  16. void Wait() { WaitForSingleObject(m_handle, INFINITE); }
  17. void Post() { ReleaseSemaphore(m_handle, 1, nullptr); }
  18. private:
  19. HANDLE m_handle;
  20. };
  21. } // namespace Common
  22. #elif defined(__APPLE__)
  23. #include <dispatch/dispatch.h>
  24. namespace Common
  25. {
  26. class Semaphore
  27. {
  28. public:
  29. Semaphore(int initial_count, int maximum_count)
  30. {
  31. m_handle = dispatch_semaphore_create(0);
  32. for (int i = 0; i < initial_count; i++)
  33. dispatch_semaphore_signal(m_handle);
  34. }
  35. ~Semaphore() { dispatch_release(m_handle); }
  36. void Wait() { dispatch_semaphore_wait(m_handle, DISPATCH_TIME_FOREVER); }
  37. void Post() { dispatch_semaphore_signal(m_handle); }
  38. private:
  39. dispatch_semaphore_t m_handle;
  40. };
  41. } // namespace Common
  42. #else
  43. #include <semaphore.h>
  44. namespace Common
  45. {
  46. class Semaphore
  47. {
  48. public:
  49. Semaphore(int initial_count, int maximum_count) { sem_init(&m_handle, 0, initial_count); }
  50. ~Semaphore() { sem_destroy(&m_handle); }
  51. void Wait() { sem_wait(&m_handle); }
  52. void Post() { sem_post(&m_handle); }
  53. private:
  54. sem_t m_handle;
  55. };
  56. } // namespace Common
  57. #endif // _WIN32