ConditionVariable
ConditionVariable 类层次结构
ConditionVariable 类提供了一种安全等待或发出状态更改信号的机制。编写多线程代码时的常见情况是使用互斥锁保护共享资源,然后释放该互斥锁以等待更改该数据。如果您不小心这样做,这可能会导致代码中的竞争条件。条件变量通过处理等待状态更改以及在此等待期间自动释放和获取互斥锁来提供此问题的安全解决方案。请注意,您无法在 ISR 上下文中对条件变量进行等待或通知调用。与 EventFlags 不同,ConditionVariable 不允许您同时等待多个事件。
ConditionVariable 类参考
数据结构 | |
struct | Waiter |
公共成员函数 | |
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 void | _add_wait_list (Waiter **wait_list, Waiter *waiter) |
static void | _remove_wait_list (Waiter **wait_list, Waiter *waiter) |
受保护的属性 | |
Mutex & | _mutex |
Waiter * | _wait_list |
ConditionVariable 示例
下面是 ConditionVariable 用法的示例,其中一个线程每 1 秒生成事件,第二个线程正在等待事件并执行操作。
#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();
}