gpt4 book ai didi

c++ - std::thread 参数的生命周期

转载 作者:可可西里 更新时间:2023-11-01 18:32:37 26 4
gpt4 key购买 nike

当参数传递给 std::thread() 时,生成新线程的线程是否会等到所有参数都完全复制到新线程本地存储中?

简单的例子:

void f()
{
int array[10];
........ //done something with array
std::thread th(someF, array); //assuming that someF accepts int[]
th.detach();
}

我是否应该自动假设所有数据在 f() 结束之前都已安全复制?我看到的一种情况是,假设 f() 不等待,而是全力以赴,th 正在尝试复制 array 正在被摧毁。

最佳答案

是的。如果复制失败,它将抛出构造线程。

§30.3.1.2 thread constructors

template explicit thread(F&& f, Args&&... args);

Requires: F and each Ti in Args shall satisfy the MoveConstructible requirements. INVOKE (DECAY_- COPY ( std::forward(f)), DECAY_COPY (std::forward(args))...) (20.8.2) shall be a valid expression. 4

Effects: Constructs an object of type thread. The new thread of execution executes INVOKE (DECAY_- COPY ( std::forward(f)), DECAY_COPY (std::forward(args))...) with the calls to DECAY_COPY being evaluated in the constructing thread. Any return value from this invocation is ignored. [ Note: This implies that any exceptions not thrown from the invocation of the copy of f will be thrown in the constructing thread, not the new thread. —end note ] If the invocation of INVOKE (DECAY_COPY ( std::forward(f)), DECAY_COPY (std::forward(args))...) terminates with an uncaught exception, std::terminate shall be called.

Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.

关于c++ - std::thread 参数的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com