在 Linux 系統下使用 C++ 進行多線程編程,你可以使用 C++11 標準庫中的 <thread>
頭文件
#include <iostream>
#include <thread>
void print_hello() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
main
函數中創建線程對象,并將要運行的函數作為參數傳遞:int main() {
// 創建線程對象,目標函數為 print_hello
std::thread t(print_hello);
// 等待線程完成
t.join();
return 0;
}
確保你的編譯器支持 C++11 標準,并使用 -std=c++11
標志進行編譯。例如,使用 g++ 編譯器:
g++ -std=c++11 main.cpp -o main -pthread
./main
這將輸出類似以下內容:
Hello from thread 1234567890
這是一個簡單的多線程示例。你可以根據需要創建更多的線程,并在它們之間共享數據或進行同步。為了實現這些功能,你可以使用 <mutex>
、<condition_variable>
、<atomic>
等頭文件。