在CentOS環境下進行C++多線程編程,你可以使用C++11標準庫中的<thread>
頭文件。以下是一個簡單的示例:
-std=c++11
選項啟用C++11特性。例如,如果你有一個名為main.cpp
的源文件,可以使用以下命令編譯:g++ -std=c++11 main.cpp -o main
main.cpp
的文件,并添加以下代碼:#include <iostream>
#include <thread>
void print_hello() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
// 創建一個線程
std::thread t(print_hello);
// 等待線程完成
t.join();
std::cout << "Hello from main thread!" << std::endl;
return 0;
}
在這個示例中,我們包含了<thread>
頭文件,并定義了一個名為print_hello
的函數,該函數將在新線程中運行。在main
函數中,我們創建了一個std::thread
對象t
,并將print_hello
函數作為參數傳遞給它。然后,我們使用join()
方法等待線程完成。最后,我們在主線程中打印一條消息。
g++ -std=c++11 main.cpp -o main
./main
你應該會看到以下輸出:
Hello from thread!
Hello from main thread!
這表明我們成功地創建了一個新線程,并在其中執行了print_hello
函數。