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