在Linux環境下使用C++進行多線程編程,你可以使用C++11標準中的 <thread>
庫。下面是一個簡單的示例,展示了如何創建多個線程并等待它們完成:
#include <iostream>
#include <thread>
#include <vector>
// 線程函數
void print_hello(int id) {
std::cout << "Hello from thread " << id << std::endl;
}
int main() {
// 創建一個線程向量
std::vector<std::thread> threads;
// 為每個數字創建一個新線程
for (int i = 0; i < 10; ++i) {
threads.emplace_back(print_hello, i);
}
// 等待所有線程完成
for (auto& t : threads) {
t.join();
}
return 0;
}
在這個示例中,我們首先包含了 <thread>
頭文件。然后定義了一個名為 print_hello
的線程函數,該函數接受一個整數參數并打印一條消息。在 main
函數中,我們創建了一個 std::vector<std::thread>
對象來存儲線程。接下來,我們使用一個循環創建了10個線程,并將它們添加到向量中。最后,我們遍歷向量并使用 join()
函數等待所有線程完成。
這只是一個簡單的示例,你可以根據自己的需求修改線程函數和線程數量。在實際應用中,你可能還需要考慮線程同步和數據競爭等問題。為了解決這些問題,你可以使用互斥鎖(std::mutex
)、條件變量(std::condition_variable
)等同步原語。