std::thread/jthread 可以退出而不执行传递的函数吗?

Yks*_*nen 3 c++ multithreading language-lawyer c++20

加入std::threadstd::jthread太快(在操作系统中实际启动线程之前)是否有可能导致线程根本不执行?或者是否保证它会简单地阻塞父线程,直到子线程启动、执行和完成?

std::stop_source我认为它应该执行是很明显的,但我的同事说如果在调用回调之前已经在 jthread 上触发了它就不必发生,因此我很困惑。

例子:

#include <thread>
#include <iostream>

void foo()
{
    std::cout << "foo()" << std::endl;
}

int main()
{
    std::jthread{foo};
    std::thread{foo}.join();
}
Run Code Online (Sandbox Code Playgroud)

这输出:

foo()
foo()
Run Code Online (Sandbox Code Playgroud)

ThreadSanitizer 也不报告问题,但我想得到标准的一些确认。

Cal*_*eth 5

构造函数确保与传递函数的调用同步

效果:新的执行线程 invoke(auto(std::forward<F>(f)), auto(std::forward<Args>(args))...) 使用在构造线程中具体化 auto 生成的值 ([conv.rval]) 来执行。此调用的任何返回值都将被忽略。

同步:构造函数调用的完成与 副本调用的开始同步f

[thread.thread.constr]

连接与线程的结束同步

同步:synchronized代表的线程完成*this与([intro.multithread])对应的成功join()返回。

[thread.thread.member]

for 也有类似的措辞jthread,只不过它可能会将 it's 传递stop_tokenf

发出信号 astop_source不会停止 a jthread,而是由调用的代码来检查stop_token并完成。