在Ubuntu上使用C++實現多線程,你可以使用C++11標準庫中的<thread>頭文件。以下是一個簡單的例子,展示了如何在C++中創建和運行多個線程。
首先,確保你的編譯器支持C++11或更高版本。在編譯時,你需要添加-std=c++11(或更高版本,如-std=c++17)標志來啟用C++11特性。
下面是一個簡單的C++多線程程序示例:
#include <iostream>
#include <thread>
// 線程函數
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 創建線程
std::thread t(helloFunction);
// 等待線程完成
t.join();
std::cout << "Hello from the main thread!" << std::endl;
return 0;
}
將上述代碼保存到文件multithread_example.cpp中,然后使用以下命令編譯:
g++ -std=c++11 multithread_example.cpp -o multithread_example
運行程序:
./multithread_example
你應該會看到來自不同線程的輸出。
如果你想要創建多個線程,可以這樣做:
#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 << "Hello from the main thread!" << std::endl;
return 0;
}
這個例子創建了5個線程,每個線程打印出自己的ID。
請注意,多線程編程可能會引入競態條件和其他并發問題。為了避免這些問題,你可能需要使用互斥鎖(std::mutex)、條件變量(std::condition_variable)等同步機制來保護共享資源。
此外,C++標準庫還提供了其他高級并發特性,如std::async、std::future和std::promise,這些可以用來實現更復雜的并發模式。