若要使用線程類std::thread
,則需包含<thread>
頭文件。
創建線程
std::thread
表示一個線程。線程對象是不可復制或賦值的,但可以移動(move),如移動構造或移動賦值。
當構造std::thread
對象時,需給構造函數輸入一個參數,該參數是一個可調用的單元,它可以是函數,函數對象,或Lambda表達式。可調用單元的返回值一般會被忽略。
以下是一個Hello World代碼示例:
// ThreadHelloWorld.cpp#include <iostream>
#include <thread>void PrintHelloWorld()
{std::cout << "Hello World!\n";
}int main(int argc, char** argv)
{std::thread helloWorldThread(PrintHelloWorld);helloWorldThread.join();return 0;
}