| OLD | NEW |
| (Empty) |
| 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 "SkTypes.h" | |
| 12 #include "SkAtomics.h" | |
| 13 | |
| 14 /** | |
| 15 * SkSemaphore is a fast mostly-user-space semaphore. | |
| 16 * | |
| 17 * A semaphore is logically an atomic integer with a few special properties: | |
| 18 * - The integer always starts at 0. | |
| 19 * - You can only increment or decrement it, never read or write it. | |
| 20 * - Increment is spelled 'signal()'; decrement is spelled 'wait()'. | |
| 21 * - If a call to wait() decrements the counter to <= 0, | |
| 22 * the calling thread sleeps until another thread signal()s it back above 0. | |
| 23 */ | |
| 24 class SkSemaphore : SkNoncopyable { | |
| 25 public: | |
| 26 // Initializes the counter to 0. | |
| 27 // (Though all current implementations could start from an arbitrary value.) | |
| 28 SkSemaphore(); | |
| 29 ~SkSemaphore(); | |
| 30 | |
| 31 // Increment the counter N times. | |
| 32 // Generally it's better to call signal(N) instead of signal() N times. | |
| 33 void signal(int N = 1); | |
| 34 | |
| 35 // Decrement the counter by 1, | |
| 36 // then if the counter is <= 0, sleep this thread until the counter is > 0. | |
| 37 void wait(); | |
| 38 | |
| 39 private: | |
| 40 // This implementation follows the general strategy of | |
| 41 // 'A Lightweight Semaphore with Partial Spinning' | |
| 42 // found here | |
| 43 // http://preshing.com/20150316/semaphores-are-surprisingly-versatile/ | |
| 44 // That article (and entire blog) are very much worth reading. | |
| 45 // | |
| 46 // We wrap an OS-provided semaphore with a user-space atomic counter that | |
| 47 // lets us avoid interacting with the OS semaphore unless strictly required: | |
| 48 // moving the count from >0 to <=0 or vice-versa, i.e. sleeping or waking th
reads. | |
| 49 struct OSSemaphore; | |
| 50 | |
| 51 SkAtomic<int> fCount; | |
| 52 OSSemaphore* fOSSemaphore; | |
| 53 }; | |
| 54 | |
| 55 #endif//SkSemaphore_DEFINED | |
| OLD | NEW |