在Ubuntu中使用C++多線程,你需要使用C++11標準庫中的<thread>
頭文件。以下是一個簡單的示例,展示了如何在Ubuntu中使用C++多線程:
-std=c++11
或-std=c++14
或-std=c++17
等選項啟用C++11支持。例如,如果你使用g++編譯器,可以這樣編譯:g++ -std=c++11 -pthread your_file.cpp -o your_program
注意:-pthread
選項用于啟用POSIX線程支持。
your_file.cpp
),并包含<thread>
頭文件:#include <iostream>
#include <thread>
void my_function() {
std::cout << "Hello from the new thread!" << std::endl;
}
main()
函數中,創建一個std::thread
對象,并將你剛剛定義的函數作為參數傳遞給它:int main() {
std::thread t(my_function);
join()
方法等待線程完成: t.join();
return 0;
}
將以上代碼片段組合在一起,你的完整C++程序應如下所示:
#include <iostream>
#include <thread>
void my_function() {
std::cout << "Hello from the new thread!" << std::endl;
}
int main() {
std::thread t(my_function);
t.join();
return 0;
}
保存文件并使用g++編譯器編譯,然后運行生成的可執行文件。你應該會看到來自新線程的消息。