Mistake on this page?
Report an issue in GitHub or email us


ConditionVariable class hierarchy

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. Note that you cannot make wait or notify calls on a condition variable from ISR context. Unlike EventFlags, ConditionVariable does not let you wait on multiple events at the same time.

ConditionVariable class reference

Data Structures
struct  Waiter
Public Member Functions
 ConditionVariable (Mutex &mutex)
void wait ()
bool wait_until (uint64_t millisec)
bool wait_for (uint32_t millisec)
void notify_one ()
void notify_all ()
 ~ConditionVariable ()
Static Protected Member Functions
static void _add_wait_list (Waiter **wait_list, Waiter *waiter)
static void _remove_wait_list (Waiter **wait_list, Waiter *waiter)
Protected Attributes

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()
    do {
        printf("Worker: Count %lu\r\n", count);

        // Wait for a condition to change

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

int main() {
    Thread thread;

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

        // Change count and signal this
        printf("Main: Set count to %lu\r\n", count);


    // Change done and signal this
    done = true;
    printf("Main: Set done\r\n");

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.