线程操作

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

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

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