条件变量
导入 <asco/sync/condition_variable.h>
头文件使用条件变量。
使用普通函数 notify_one()
唤醒一个正在等待的协程,使用普通函数 notify_all()
唤醒所有正在等待的协程。
使用 wait()
函数等待条件变量,协程 wait()
的返回类型为 future_void_inline
,需要 co_await
才能开始执行。
wait()
函数与标准库的 std::condition_variable::wait()
不同,仅接收一个条件判断函数,条件判断的原子性需要调用者自行保证,
因此条件变量的原子性在某些情况下可以避免使用锁而是使用原子变量保证。
而协程进入等待队列和挂起当前协程两个操作的原子性由此类本身保证。
future<int> async_main() {
condition_variable decl_local(cv);
atomic_bool decl_local(flag, new atomic_bool{false});
auto task = []() -> future_void {
condition_variable coro_local(cv);
atomic_bool coro_local(flag);
co_await cv.wait([&flag]{ return flag.load(); });
std::cout << "cv notified" << std::endl;
co_return {};
}();
co_await this_coro::sleep_for(1s);
flag.notify_one();
co_await task;
co_return 0;
}