In C++20 Standard library std::condition_variable_any::wait() family support std::stop_token for generalized thread cancellation, but std::condition_variable does not.
P0660R10 Stop Token and Joining Thread, Rev 10 says:
New in R6
- User
condition_variable_anyinstead ofconsition_variableto avoid all possible races, deadlocks, and unintended undefined behavior.
I think that the following code safely emulates condition_variable::wait() with stop_token cancellation. What am I missing? Is there subtle edge case?
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();
}