執行緒操作

當你啟動一個執行緒時,它將執行直到它完成。

通常,在某些時候,你需要(可能 - 執行緒可能已經完成)等待執行緒完成,因為你想要使用結果作為示例。

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

//Doing some other stuff

//We need 'n' now!
//Wait for the thread to finish - if it is not already done
thread.join();

//Now 'n' has the result of the calculation done in the seperate thread
std::cout << n << '\n';

你也可以通過執行緒,讓它自由執行:

std::thread thread{ doSomething };

//Detaching the thread, we don't need it anymore (for whatever reason)
thread.detach();

//The thread will terminate when it is done, or when the main thread returns