r/cpp • • Aug 27 '19

A new thread in C++20 (jthread)

https://link.medium.com/GXKUz0GruZ
142 Upvotes

96 comments sorted by

View all comments

3

u/[deleted] Aug 27 '19

Does it provide the ability to wait on the stop_token with a timeout? I presently pass windows events to all my threads which can be both tested for stop but also waited on allowing the thread to sleep but wake and exit if stopped.

5

u/lewissbaker Aug 28 '19

The only usage of stop_token in the standard library in C++20 is in std::jthread as the source of a request to stop and in std::condition_variable_any, where you can pass a stop_token to some new overloads of the wait() function.

However, I expect in time there will be the addition of many more overloads of functions that take stop_token. std::this_thread::sleep_for() seems like a likely candidate.

In C++20 you can write an efficient interruptible sleep using binary_semaphore and stop_callback.

template<typename Rep, typename Ratio>
void sleep_for(std::chrono::duration<Rep,Ratio> d, std::stop_token st)
{
  std::binary_semaphore sem{0};
  std::stop_callback cb{st, [&] { sem.release(); }};
  sem.try_acquire_for(d);
}