Skip to content

Commit 833ae8c

Browse files
author
Amanda Butler
authored
Merge pull request #318 from c1728p9/condition_variable
Add documentation for the ConditionVariable class
2 parents 6514f51 + 3712328 commit 833ae8c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
## ConditionVariable
2+
3+
The ConditionVariable class provides a mechanism to safely wait for or signal state changes. A common scenario when writing multithreaded code is to protect shared resources with a mutex and then release that mutex to wait for a change of that data. If you do not do this carefully, this can lead to a race condition in the code. A condition variable provides a safe solution to this problem by handling the wait for a state change, along with releasing and acquiring the mutex automatically during this waiting period.
4+
5+
### ConditionVariable class reference
6+
7+
[![View code](https://www.mbed.com/embed/?type=library)](https://os-doc-builder.test.mbed.com/docs/v5.7/mbed-os-api-doxy/classrtos_1_1_condition_variable.html)
8+
9+
### ConditionVariable example
10+
11+
Below is an example of ConditionVariable usage, where one thread is generating events every 1s, and the second thread is waiting for the events and executing an action.
12+
13+
```
14+
#include "mbed.h"
15+
16+
Mutex mutex;
17+
ConditionVariable cond(mutex);
18+
19+
// These variables are protected by locking mutex
20+
uint32_t count = 0;
21+
bool done = false;
22+
23+
void worker_thread()
24+
{
25+
mutex.lock();
26+
do {
27+
printf("Worker: Count %lu\r\n", count);
28+
29+
// Wait for a condition to change
30+
cond.wait();
31+
32+
} while (!done);
33+
printf("Worker: Exiting\r\n");
34+
mutex.unlock();
35+
}
36+
37+
int main() {
38+
Thread thread;
39+
thread.start(worker_thread);
40+
41+
for (int i = 0; i < 5; i++) {
42+
43+
mutex.lock();
44+
// Change count and signal this
45+
count++;
46+
printf("Main: Set count to %lu\r\n", count);
47+
cond.notify_all();
48+
mutex.unlock();
49+
50+
wait(1.0);
51+
}
52+
53+
mutex.lock();
54+
// Change done and signal this
55+
done = true;
56+
printf("Main: Set done\r\n");
57+
cond.notify_all();
58+
mutex.unlock();
59+
60+
thread.join();
61+
}
62+
```

0 commit comments

Comments
 (0)