【发布时间】:2021-05-24 07:35:15
【问题描述】:
在 C++20 标准库中,std::condition_variable_any::wait() 系列支持 std::stop_token 用于通用线程取消,但 std::condition_variable 不支持。
P0660R10 Stop Token and Joining Thread, Rev 10 说:
R6 中的新功能
- 使用
condition_variable_any而不是consition_variable以避免所有可能的竞争、死锁和意外的未定义行为。
我认为以下代码可以安全地模拟 condition_variable::wait() 并取消 stop_token。我错过了什么?是否存在微妙的边缘情况?
template<class Lock, class Predicate>
bool cv_wait_with_stoken(
std::condition_variable& cv, Lock& lock, std::stop_token stoken, Predicate pred)
{
std::stop_callback callback{ stoken, [&cv]{ cv.notify_all(); } };
while (!stoken.stop_requested()) {
if (pred())
return true;
cv.wait(lock);
}
return pred();
}
【问题讨论】:
标签: c++ multithreading thread-safety c++20