[英]std::this_thread::yield() vs std::this_thread::sleep_for()
[英]Where is std::this_thread for jthread?
無法弄清楚jthread
的std::this_thread
在哪里?
我有一個 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();
});
}
我如何在jthread
上調用它?
理論上,下面的程序會在 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;
}
jthread構造函數接受一個 function,它以 std::stop_token 作為它的第一個參數,它將由 jthread 從它的內部 stop_source 傳入。
這是一個例子:
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();
住在Godbolt上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.