C++ 线程操作

示例

当启动线程时,它将一直执行到完成为止。

通常,在某个时候,您需要(可能-线程可能已经完成)等待线程完成,因为您想使用例如结果。

int n;
std::thread thread{ calculateSomething, std::ref(n) };

//做其他事情

//我们现在需要'n'!
//等待线程完成-如果尚未完成
thread.join();

//现在,“ n”具有在单独线程中完成的计算结果
std::cout << n << '\n';


您还可以detach使用线程,使其自由执行:

std::thread thread{ doSomething };

//分离线程,我们不再需要它(无论出于何种原因)
thread.detach();

//该线程将在完成或主线程返回时终止