[英]Where is std::this_thread for jthread?
Can't figure out where is std::this_thread
for jthread
?无法弄清楚
jthread
的std::this_thread
在哪里?
I have a function that theoretically makes a jthread
sleep until a cancellation is requested:我有一个 function 理论上让
jthread
休眠直到请求取消:
template<typename Rep, typename Period>
void sleep_for(const std::chrono::duration<Rep, Period>& d, const std::stop_token& token)
{
std::condition_variable cv;
std::mutex mutex;
std::unique_lock<std::mutex> lock{ mutex };
std::stop_callback stop_wait{ token, [&cv]()
{
cv.notify_one(); }
};
cv.wait_for(lock, d, [&token]()
{
return token.stop_requested();
});
}
How do I call it on jthread
?我如何在
jthread
上调用它?
Theoretically the program below exits within 1 second:理论上,下面的程序会在 1 秒内退出:
int main()
{
std::jthread t([]()
{
//where do I get `stop_token`?
sleep_for(std::chrono::seconds(5), std::this_jthread::get_stop_token());
});
std::this_thread::sleep_for(std::chrono::seconds(1));
t.request_stop();
return 0;
}
The jthread constructor accepts a function that takes a std::stop_token as its first argument, which will be passed in by the jthread from its internal stop_source.
jthread构造函数接受一个 function,它以 std::stop_token 作为它的第一个参数,它将由 jthread 从它的内部 stop_source 传入。
Here is an example:这是一个例子:
std::jthread t([](std::stop_token stop_token)
{
while(!stop_token.stop_requested()) {
//Process data...
std::this_thread::sleep_for(std::chrono::seconds(5));
}
});
std::this_thread::sleep_for(std::chrono::seconds(1));
t.request_stop();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.