如何使用 std::jthread::get_stop_token()?

Meh*_*dad 6 c++ synchronization cancellation stdthread c++20

我很困惑它std::jthread::get_stop_token是如何设计的,因为它似乎有一个固有的竞争条件。

也就是说,执行线程不能简单地调用std::jthread自身(如本例所示),因为它不能保证该std::jthread对象在它开始执行时实际上已构造完毕。在我看来,对于一个线程来说get_stop_token,要使用自己的 ,它需要(至少)一个额外的事件(比如std::latch),仅用于与它自己的构造进行同步。

但是,我在网上没有看到任何有关此问题的示例或提及,因此在我看来,这可能不是预期的用法。它确实看起来相当笨重且容易出错,并且可能效率低下,因为它需要工作线程在继续之前阻塞主线程。

那么应该如何get_stop_token使用呢?
有没有一个简单的例子来说明 的正确、预期用法std::jthread::get_stop_token()

bar*_*top 2

从这里的示例看来,get_stop_token实际上并不意味着客户端代码可以使用它。它由 于幕后调用,std::jthread并传递给 所调用的函数std::jthread。看来这就是必须要做的事情

#include <thread>
#include <iostream>
 
void f(std::stop_token stop_token, int value)
{
    while (!stop_token.stop_requested()) {
    }
}
 
int main()
{
    std::jthread thread(f, 5); 
}
Run Code Online (Sandbox Code Playgroud)