Mistake on this page?
Report an issue in GitHub or email us
ConditionVariable.h
1 /* Mbed Microcontroller Library
2  * Copyright (c) 2017-2019 ARM Limited
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20  * SOFTWARE.
21  */
22 #ifndef CONDITIONVARIABLE_H
23 #define CONDITIONVARIABLE_H
24 
25 #include <stdint.h>
26 #include "rtos/mbed_rtos_types.h"
27 #include "rtos/Mutex.h"
28 #include "rtos/Semaphore.h"
29 
30 #include "platform/NonCopyable.h"
31 
32 #if MBED_CONF_RTOS_PRESENT || defined(DOXYGEN_ONLY)
33 
34 namespace rtos {
35 /** \addtogroup rtos-public-api */
36 /** @{*/
37 
38 struct Waiter;
39 /**
40  * \defgroup rtos_ConditionVariable ConditionVariable class
41  * @{
42  */
43 
44 /** The ConditionVariable class is a synchronization primitive that allows
45  * threads to wait until a particular condition occurs.
46  *
47  * Use the condition variable in conjunction with a mutex to safely wait for
48  * or notify waiters of condition changes to a resource accessible by multiple
49  * threads.
50  *
51  * The thread that intends to wait on a ConditionVariable must:
52  * - Acquire a lock on a mutex.
53  * - Execute `wait`, `wait_for` or `wait_until`. While the thread is waiting,
54  * the mutex is unlocked.
55  * - When the condition variable has been notified, or in the case of `wait_for`
56  * and `wait_until` the timeout expires, the thread is awakened.
57  *
58  * The thread that intends to notify a ConditionVariable must:
59  * - Acquire a lock on the mutex used to construct the condition variable.
60  * - Execute `notify_one` or `notify_all` on the condition variable.
61  *
62  * All threads waiting on the condition variable wake when
63  * `ConditionVariable::notify_all` is called.
64  * At least one thread waiting on the condition variable wakes
65  * when `ConditionVariable::notify_one` is called.
66  *
67  * While a thread is waiting for notification of a
68  * ConditionVariable, it releases the lock held on the mutex.
69  * The ConditionVariable reacquires the mutex lock before exiting the wait
70  * function.
71  *
72  * #### Unspecified behavior
73  * - The thread that is unblocked on `ConditionVariable::notify_one` is
74  * unspecified if there are multiple waiters.
75  * - When `ConditionVariable::notify_one` or `ConditionVariable::notify_all` is
76  * called and there are one or more waiters, and one or more threads
77  * attempting to acquire the condition variable's mutex, the order in which the mutex is
78  * acquired is unspecified.
79  * - Spurious notifications (not triggered by the application) can occur.
80  *
81  * #### Undefined behavior
82  * - Calling wait if the mutex is not locked by the current thread is undefined
83  * behavior.
84  * - The order in which waiting threads acquire the condition variable's
85  * mutex after `ConditionVariable::notify_all` is called is undefined.
86  * - The behavior of `ConditionVariable::wait` and `ConditionVariable::wait_for`
87  * is undefined if the condition variable's mutex is locked more than once by
88  * the calling thread.
89  *
90  * @note Synchronization level: Thread safe
91  *
92  * Example:
93  *
94  * @code
95  * #include "mbed.h"
96  *
97  * Mutex mutex;
98  * ConditionVariable cv(mutex);
99  *
100  * // These variables are protected by locking the mutex.
101  * uint32_t work_count = 0;
102  * bool done = false;
103  *
104  * void worker_thread()
105  * {
106  * // Acquire lock on mutex before accessing protected variables and waiting.
107  * mutex.lock();
108  *
109  * while (done == false) {
110  * printf("Worker thread: Count: %lu\r\n", work_count);
111  *
112  * // Wait for main thread to notify the condition variable.
113  * printf("Worker thread: Waiting\r\n");
114  * cv.wait();
115  * }
116  *
117  * printf("Worker: Exiting\r\n");
118  *
119  * // The condition variable acquires the lock when exiting the `wait` function.
120  * // Unlock mutex when exiting the thread.
121  * mutex.unlock();
122  * }
123  *
124  * int main()
125  * {
126  * Thread thread;
127  * thread.start(worker_thread);
128  *
129  * for (int i = 0; i < 5; i++) {
130  * // Acquire lock on mutex before modifying variables and notifying.
131  * mutex.lock();
132  *
133  * // Change count and notify waiters.
134  * work_count++;
135  * printf("Main thread: Set count to: %lu\r\n", work_count);
136  * printf("Main thread: Notifying worker thread\r\n");
137  * cv.notify_all();
138  *
139  * // Mutex must be unlocked before the worker thread can acquire it.
140  * mutex.unlock();
141  *
142  * wait(1.0);
143  * }
144  *
145  * // Change done and notify waiters of this.
146  * mutex.lock();
147  * done = true;
148  * cv.notify_all();
149  * mutex.unlock();
150  *
151  * thread.join();
152  *
153  * printf("Main: Exiting\r\n");
154  * }
155  * @endcode
156  */
157 
158 class ConditionVariable : private mbed::NonCopyable<ConditionVariable> {
159 public:
160  /** Create and initialize a ConditionVariable object.
161  *
162  * @note You cannot call this function from ISR context.
163  */
164  ConditionVariable(Mutex &mutex);
165 
166  /** Wait for a notification.
167  *
168  * Wait causes the current thread to block until the condition variable
169  * receives a notification from another thread.
170  *
171  * @note - The thread calling this function must be the owner of the
172  * ConditionVariable's mutex, and it must be locked exactly once.
173  *
174  * @note - Spurious notifications can occur, so the caller of this API
175  * should check to make sure the condition the caller is waiting on has
176  * been met.
177  *
178  * @note - The current thread releases the lock while inside the wait
179  * function and reacquires it upon exiting the function.
180  *
181  * Example:
182  * @code
183  * mutex.lock();
184  *
185  * while (!condition_met) {
186  * cond.wait();
187  * }
188  *
189  * function_to_handle_condition();
190  *
191  * mutex.unlock();
192  * @endcode
193  *
194  * @note You cannot call this function from ISR context.
195  */
196  void wait();
197 
198  /** Wait for a notification until the specified time.
199  *
200  * Wait until causes the current thread to block until the condition
201  * variable is notified, or a specific time given by millisec parameter is
202  * reached.
203  *
204  * @param millisec Absolute end time referenced to `Kernel::get_ms_count()`
205  * @return `true` if a timeout occurred, `false` otherwise.
206  *
207  * @note - The thread calling this function must be the owner of the
208  * ConditionVariable's mutex, and it must be locked exactly once.
209  *
210  * @note - Spurious notifications can occur, so the caller of this API
211  * should check to make sure the condition the caller is waiting on has
212  * been met.
213  *
214  * @note - The current thread releases the lock while inside the wait
215  * function and reacquires it upon exiting the function.
216  *
217  * Example:
218  * @code
219  * mutex.lock();
220  * uint64_t end_time = Kernel::get_ms_count() + COND_WAIT_TIMEOUT;
221  *
222  * while (!condition_met) {
223  * if (cond.wait_until(end_time)) {
224  * break;
225  * }
226  * }
227  *
228  * if (condition_met) {
229  * function_to_handle_condition();
230  * }
231  *
232  * mutex.unlock();
233  * @endcode
234  *
235  * @note You cannot call this function from ISR context.
236  */
237  bool wait_until(uint64_t millisec);
238 
239  /** Wait for a notification or timeout.
240  *
241  * `Wait for` causes the current thread to block until the condition
242  * variable receives a notification from another thread, or the timeout
243  * specified by the millisec parameter is reached.
244  *
245  * @param millisec Timeout value or osWaitForever in case of no timeout.
246  * @return `true` if a timeout occurred, `false` otherwise.
247  *
248  * @note - The thread calling this function must be the owner of the
249  * ConditionVariable's mutex, and it must be locked exactly once.
250  *
251  * @note - Spurious notifications can occur, so the caller of this API
252  * should check to make sure the condition the caller is waiting on has
253  * been met.
254  *
255  * @note - The current thread releases the lock while inside the wait
256  * function and reacquire it upon exiting the function.
257  *
258  * Example:
259  * @code
260  * mutex.lock();
261  *
262  * while (!condition_met) {
263  * cond.wait_for(MAX_SLEEP_TIME);
264  * if (!condition_met) {
265  * do_other_work_while_condition_false();
266  * }
267  * }
268  *
269  * if (condition_met) {
270  * function_to_handle_condition();
271  * }
272  *
273  * mutex.unlock();
274  * @endcode
275  *
276  * @note You cannot call this function from ISR context.
277  */
278  bool wait_for(uint32_t millisec);
279 
280  /** Notify one waiter on this condition variable that a condition changed.
281  *
282  * This function unblocks one of the threads waiting for the condition
283  * variable.
284  *
285  * @note - The thread calling this function must be the owner of the
286  * ConditionVariable's mutex.
287  *
288  * @note - The thread that is unblocked on ConditionVariable::notify_one is
289  * undefined if there are multiple waiters.
290  *
291  * @note You cannot call this function from ISR context.
292  */
293  void notify_one();
294 
295  /** Notify all waiters on this condition variable that a condition changed.
296  *
297  * This function unblocks all of the threads waiting for the condition
298  * variable.
299  *
300  * @note - The thread calling this function must be the owner of the
301  * ConditionVariable's mutex.
302  *
303  * @note - If there are one or more waiters and one or more threads
304  * attempting to acquire the condition variable's mutex the order in which
305  * the mutex is acquired is undefined.
306  *
307  * @note You cannot call this function from ISR context.
308  */
309  void notify_all();
310 
311  /** ConditionVariable destructor.
312  *
313  * @note You cannot call this function from ISR context.
314  */
316 
317 #if !defined(DOXYGEN_ONLY)
318 protected:
319  struct Waiter {
320  Waiter();
321  Semaphore sem;
322  Waiter *prev;
323  Waiter *next;
324  bool in_list;
325  };
326 
327  static void _add_wait_list(Waiter **wait_list, Waiter *waiter);
328  static void _remove_wait_list(Waiter **wait_list, Waiter *waiter);
329  Mutex &_mutex;
330  Waiter *_wait_list;
331 #endif // !defined(DOXYGEN_ONLY)
332 };
333 
334 /** @}*/
335 /** @}*/
336 } // namespace rtos
337 #endif
338 
339 #endif
void wait()
Wait for a notification.
The Semaphore class is used to manage and protect access to a set of shared resources.
Definition: Semaphore.h:47
Prevents generation of copy constructor and copy assignment operator in derived classes.
Definition: NonCopyable.h:169
void notify_all()
Notify all waiters on this condition variable that a condition changed.
The Mutex class is used to synchronize the execution of threads.
Definition: Mutex.h:68
ConditionVariable(Mutex &mutex)
Create and initialize a ConditionVariable object.
bool wait_until(uint64_t millisec)
Wait for a notification until the specified time.
~ConditionVariable()
ConditionVariable destructor.
The ConditionVariable class is a synchronization primitive that allows threads to wait until a partic...
bool wait_for(uint32_t millisec)
Wait for a notification or timeout.
void notify_one()
Notify one waiter on this condition variable that a condition changed.
Definition: TaskBase.h:25
Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.