std::thread 移动构造函数

std::thread move constructor

我最近看了这篇 std::thread 参考资料。

对于移动构造函数,它说:

thread( thread&& other ); 

Move constructor. Constructs the thread object to represent the thread of execution that was represented by other. After this call other no longer represents a thread of execution.

此外,在下面的示例中有这些行:

int n=0;
std::thread t3(f2, n);
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread

我不明白线程 t3t4 到底发生了什么? t4 是否等到 t3 完成执行? t3 不再是线程是什么意思?

std::thread 不是话题。它是底层操作系统提供的线程的表示,您可以使用它来操作线程。这就像 car 对象不是真正的汽车。

move 将表示的线程从一个 std::thread 移动到另一个。在move之后,t3就是一个胆小鬼std::threadstd::thread 对象仍然存在,但是 t3 没有引用任何实际的系统线程。 t4 现在表示以前由 t3 表示的线程,但它不会等待,除非您调用 join