在Ubuntu上進行C++多線程編程,你可以使用C++11標準庫中提供的<thread>頭文件。以下是一個簡單的例子,展示了如何創建和使用線程:
#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;
}
在這個例子中,我們首先包含了<thread>頭文件。然后定義了一個簡單的函數helloFunction,它將在新線程中執行。在main函數中,我們使用std::thread創建了一個新線程,并將helloFunction作為參數傳遞給它。最后,我們調用t.join()等待線程完成執行。
要編譯這個程序,你需要使用支持C++11的編譯器,并且鏈接線程庫??梢允褂靡韵旅顏砭幾g:
g++ -std=c++11 -pthread your_program.cpp -o your_program
這里-std=c++11告訴編譯器使用C++11標準,而-pthread是鏈接線程庫的選項。
如果你想要在線程之間共享數據或者同步它們的執行,你可以使用<mutex>、<condition_variable>、<atomic>等同步原語。
下面是一個使用互斥鎖(std::mutex)來保護共享資源的例子:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 創建一個互斥鎖
void printMessage(const std::string& msg) {
mtx.lock(); // 鎖定互斥鎖
std::cout << msg << std::endl;
mtx.unlock(); // 解鎖互斥鎖
}
int main() {
std::thread t1(printMessage, "Hello from thread 1!");
std::thread t2(printMessage, "Hello from thread 2!");
t1.join();
t2.join();
return 0;
}
在這個例子中,我們定義了一個全局的std::mutex對象mtx,并在printMessage函數中使用lock()和unlock()方法來確保每次只有一個線程可以訪問std::cout。
請注意,從C++17開始,推薦使用std::lock_guard或std::unique_lock來自動管理鎖的生命周期,這樣可以避免忘記解鎖導致的死鎖問題。下面是使用std::lock_guard的例子:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void printMessage(const std::string& msg) {
std::lock_guard<std::mutex> lock(mtx); // 自動管理鎖
std::cout << msg << std::endl;
}
int main() {
std::thread t1(printMessage, "Hello from thread 1!");
std::thread t2(printMessage, "Hello from thread 2!");
t1.join();
t2.join();
return 0;
}
在這個版本中,我們使用了std::lock_guard,它在構造時鎖定互斥鎖,在析構時自動解鎖,這樣可以確保即使在函數執行過程中拋出異常,鎖也會被正確釋放。