Skip to content

Add documentation for the ConditionVariable class #318

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 11, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions docs/reference/api/rtos/ConditionVariable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
## ConditionVariable

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.

### ConditionVariable class reference

[![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)

### ConditionVariable example

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.

```
#include "mbed.h"

Mutex mutex;
ConditionVariable cond(mutex);

// These variables are protected by locking mutex
uint32_t count = 0;
bool done = false;

void worker_thread()
{
mutex.lock();
do {
printf("Worker: Count %lu\r\n", count);

// Wait for a condition to change
cond.wait();

} while (!done);
printf("Worker: Exiting\r\n");
mutex.unlock();
}

int main() {
Thread thread;
thread.start(worker_thread);

for (int i = 0; i < 5; i++) {

mutex.lock();
// Change count and signal this
count++;
printf("Main: Set count to %lu\r\n", count);
cond.notify_all();
mutex.unlock();

wait(1.0);
}

mutex.lock();
// Change done and signal this
done = true;
printf("Main: Set done\r\n");
cond.notify_all();
mutex.unlock();

thread.join();
}
```