在Linux環境下,C++可以通過多種方式實現并發控制。以下是一些常用的方法:
互斥鎖(Mutexes):
<mutex>
頭文件中的std::mutex
類來實現互斥鎖。lock()
和unlock()
成員函數來加鎖和解鎖。std::lock_guard
或std::unique_lock
來自動管理鎖的生命周期。條件變量(Condition Variables):
<condition_variable>
頭文件中的std::condition_variable
類。原子操作(Atomic Operations):
<atomic>
頭文件中的原子類型,如std::atomic<int>
。信號量(Semaphores):
sem_wait()
、sem_post()
等函數。std::counting_semaphore
或std::binary_semaphore
。讀寫鎖(Read-Write Locks):
<shared_mutex>
頭文件中的std::shared_mutex
類。線程(Threads):
<thread>
頭文件中的std::thread
類來創建和管理線程。join()
和detach()
來控制線程的生命周期。屏障(Barriers):
<barrier>
頭文件中的std::barrier
類(C++20)。鎖(Locks):
<shared_mutex>
頭文件中的std::shared_lock
類。下面是一個簡單的例子,展示了如何使用互斥鎖來保護共享資源:
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mtx; // 全局互斥鎖
int shared_data = 0; // 共享數據
void increment_shared_data() {
mtx.lock(); // 加鎖
++shared_data; // 修改共享數據
mtx.unlock(); // 解鎖
}
int main() {
std::thread t1(increment_shared_data);
std::thread t2(increment_shared_data);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
在實際應用中,應該盡量減少鎖的使用范圍,避免死鎖,并且考慮使用更高級的同步機制來提高性能。