Brian Silverman | f5f3490 | 2015-03-29 17:57:59 -0400 | [diff] [blame^] | 1 | #ifndef AOS_COMMON_EVENT_H_ |
| 2 | #define AOS_COMMON_EVENT_H_ |
| 3 | |
| 4 | #include "aos/linux_code/ipc_lib/aos_sync.h" |
| 5 | |
| 6 | namespace aos { |
| 7 | |
| 8 | // An abstraction of an event which is easy to implement for Linux and in other |
| 9 | // environments. |
| 10 | // On Linux at least, this is definitely safe for passing through C code with |
| 11 | // memcpy etc. |
| 12 | // |
| 13 | // An event is either "set" or "unset". Any thread can transition it between |
| 14 | // these two states and other threads can wait for an unset->set transition. |
| 15 | // This is not a particularly powerful synchronization primitive, but it can be |
| 16 | // much easier to use than more complicated ones in some situations. The name is |
| 17 | // taken from Python's implementation of the same thing. |
| 18 | // |
| 19 | // An event is equivalent to a semaphore which is either set to 0 or infinity. |
| 20 | // It is also equivalent to a condition variable with the monitored condition |
| 21 | // being "is it set or not". |
| 22 | // |
| 23 | // IMPORTANT: You can NOT use this to successfully replace a standard condition |
| 24 | // variable in most cases. When the condition being monitored changes separately |
| 25 | // from the actual state of the condition variable/event, there WILL be race |
| 26 | // conditions if you try to use this class. |
| 27 | // |
| 28 | // It is undefined behavior to destroy an Event while there are current |
| 29 | // Wait()ers. |
| 30 | class Event { |
| 31 | public: |
| 32 | // Creates an unset event. |
| 33 | Event(); |
| 34 | // There must be no waiters when an Event is destroyed. |
| 35 | ~Event() = default; |
| 36 | |
| 37 | // Waits for the event to be set. Returns immediately if it is already set. |
| 38 | void Wait(); |
| 39 | |
| 40 | // Wakes up all Wait()ers and sets the event (atomically). |
| 41 | void Set(); |
| 42 | // Unsets the event so future Wait() callers will block instead of returning |
| 43 | // immediately. |
| 44 | // Returns true if the event was previously set. |
| 45 | bool Clear(); |
| 46 | |
| 47 | private: |
| 48 | aos_futex impl_; |
| 49 | }; |
| 50 | |
| 51 | } // namespace aos |
| 52 | |
| 53 | #endif // AOS_COMMON_EVENT_H_ |