在 Linux 上設計 C++ 多線程程序時,需要考慮以下幾個方面:
<iostream>
、<thread>
、<mutex>
、<condition_variable>
等頭文件。#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex
來保護一個全局變量。std::mutex mtx;
std::condition_variable
來實現這一功能。std::condition_variable cv;
void thread_function(int id) {
// 線程任務代碼
}
std::thread
類創建線程,并將線程函數作為參數傳遞。例如:std::thread t1(thread_function, 1);
std::thread t2(thread_function, 2);
join()
或 detach()
方法等待線程完成。join()
方法會阻塞當前線程,直到被調用 join()
的線程完成。detach()
方法則會將線程設置為分離狀態,當前線程不會等待該線程完成。t1.join();
t2.join();
std::unique_lock<std::mutex> lock(mtx);
// 訪問共享資源
cv.notify_one(); // 通知其他線程
這是一個簡單的 C++ 多線程示例:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
int shared_resource = 0;
void thread_function(int id) {
std::unique_lock<std::mutex> lock(mtx);
std::cout << "Thread " << id << " is waiting.\n";
cv.wait(lock); // 等待條件變量
shared_resource += 1;
std::cout << "Thread " << id << " has incremented the shared resource to " << shared_resource << ".\n";
cv.notify_one(); // 通知其他線程
}
int main() {
std::thread t1(thread_function, 1);
std::thread t2(thread_function, 2);
t1.join();
t2.join();
return 0;
}
這個示例中,兩個線程等待一個條件變量,然后遞增共享資源。當條件變量被通知時,線程會繼續執行并更新共享資源。