在 Linux 下使用 C++ 實現多線程,通??梢允褂?C++11 標準庫提供的 <thread>
頭文件。以下是一個簡單的示例,展示如何創建和管理多個線程:
#include <iostream>
#include <thread>
#include <vector>
// 線程函數
void helloFunction(int id) {
std::cout << "Hello from thread " << id << std::endl;
}
int main() {
const int numThreads = 5;
std::vector<std::thread> threads;
// 創建多個線程
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(helloFunction, i);
}
// 等待所有線程完成
for (auto& th : threads) {
th.join();
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
包含頭文件:
#include <thread>
:提供線程支持。#include <vector>
:用于存儲線程對象。#include <iostream>
:用于輸入輸出操作。線程函數:
void helloFunction(int id)
是一個簡單的函數,它接受一個整數參數并打印一條消息。創建線程:
std::thread
創建線程對象,并將線程函數和參數傳遞給它。threads.emplace_back(helloFunction, i);
創建一個新線程并立即開始執行 helloFunction(i)
。等待線程完成:
join()
方法等待每個線程完成。如果不調用 join()
,主線程可能會在子線程完成之前退出,導致未定義行為。編譯和運行:
g++ -std=c++11 -pthread your_program.cpp -o your_program
./your_program
std::mutex
)或其他同步機制來保護共享數據。通過以上步驟,你可以在 Linux 下使用 C++ 實現多線程編程。