SkSemaphore.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright 2015 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #ifndef SkSemaphore_DEFINED
  8. #define SkSemaphore_DEFINED
  9. #include "include/core/SkTypes.h"
  10. #include "include/private/SkOnce.h"
  11. #include <atomic>
  12. class SkSemaphore {
  13. public:
  14. constexpr SkSemaphore(int count = 0) : fCount(count), fOSSemaphore(nullptr) {}
  15. // Cleanup the underlying OS semaphore.
  16. ~SkSemaphore();
  17. // Increment the counter n times.
  18. // Generally it's better to call signal(n) instead of signal() n times.
  19. void signal(int n = 1);
  20. // Decrement the counter by 1,
  21. // then if the counter is < 0, sleep this thread until the counter is >= 0.
  22. void wait();
  23. // If the counter is positive, decrement it by 1 and return true, otherwise return false.
  24. bool try_wait();
  25. private:
  26. // This implementation follows the general strategy of
  27. // 'A Lightweight Semaphore with Partial Spinning'
  28. // found here
  29. // http://preshing.com/20150316/semaphores-are-surprisingly-versatile/
  30. // That article (and entire blog) are very much worth reading.
  31. //
  32. // We wrap an OS-provided semaphore with a user-space atomic counter that
  33. // lets us avoid interacting with the OS semaphore unless strictly required:
  34. // moving the count from >=0 to <0 or vice-versa, i.e. sleeping or waking threads.
  35. struct OSSemaphore;
  36. void osSignal(int n);
  37. void osWait();
  38. std::atomic<int> fCount;
  39. SkOnce fOSSemaphoreOnce;
  40. OSSemaphore* fOSSemaphore;
  41. };
  42. inline void SkSemaphore::signal(int n) {
  43. int prev = fCount.fetch_add(n, std::memory_order_release);
  44. // We only want to call the OS semaphore when our logical count crosses
  45. // from <0 to >=0 (when we need to wake sleeping threads).
  46. //
  47. // This is easiest to think about with specific examples of prev and n.
  48. // If n == 5 and prev == -3, there are 3 threads sleeping and we signal
  49. // SkTMin(-(-3), 5) == 3 times on the OS semaphore, leaving the count at 2.
  50. //
  51. // If prev >= 0, no threads are waiting, SkTMin(-prev, n) is always <= 0,
  52. // so we don't call the OS semaphore, leaving the count at (prev + n).
  53. int toSignal = SkTMin(-prev, n);
  54. if (toSignal > 0) {
  55. this->osSignal(toSignal);
  56. }
  57. }
  58. inline void SkSemaphore::wait() {
  59. // Since this fetches the value before the subtract, zero and below means that there are no
  60. // resources left, so the thread needs to wait.
  61. if (fCount.fetch_sub(1, std::memory_order_acquire) <= 0) {
  62. this->osWait();
  63. }
  64. }
  65. #endif//SkSemaphore_DEFINED