在Linux環境下使用C++實現并發控制,通常會涉及到多線程編程和同步機制。以下是一些基本的步驟和概念,以及如何在C++中使用它們:
多線程編程:
<thread>
庫來創建和管理線程。同步機制:
下面是一個簡單的例子,展示了如何使用<thread>
和<mutex>
來實現并發控制:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 創建一個互斥鎖
void print_block(int n, char c) {
mtx.lock(); // 加鎖
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
mtx.unlock(); // 解鎖
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join(); // 等待線程1完成
th2.join(); // 等待線程2完成
return 0;
}
在這個例子中,print_block
函數用于打印字符直到達到指定的數量。我們使用std::mutex
來確保同一時間只有一個線程可以執行打印操作。
除了互斥鎖,C++標準庫還提供了其他同步原語,例如:
std::lock_guard
:一個方便的RAII風格的互斥鎖管理類,它在構造時鎖定互斥鎖,在析構時自動解鎖。std::unique_lock
:一個更靈活的互斥鎖管理類,它允許延遲鎖定、時間鎖定、遞歸鎖定等。std::condition_variable
:用于線程間的等待/通知機制。std::atomic
:用于實現原子操作,保證操作的原子性,避免數據競爭。下面是使用std::lock_guard
和std::condition_variable
的一個例子:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{return ready;}); // 等待直到ready為true
std::cout << "Thread " << id << '\n';
}
void go() {
std::lock_guard<std::mutex> lck(mtx);
ready = true;
cv.notify_all(); // 通知所有等待的線程
}
int main() {
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(print_id, i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto &th : threads) th.join();
return 0;
}
在這個例子中,我們創建了10個線程,它們都在等待一個信號。主線程通過調用go
函數來發出信號,使得所有等待的線程同時開始執行。
并發編程是一個復雜的主題,需要仔細考慮線程安全和資源管理。在實際應用中,還需要考慮死鎖、活鎖、饑餓等問題,并采取相應的預防措施。