在C++中,互斥鎖(mutex)是一種同步原語,用于確保多個線程在訪問共享資源時不會發生沖突。C++標準庫中的<mutex>頭文件提供了互斥鎖的實現。以下是一個簡單的示例,展示了如何使用互斥鎖實現線程同步:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 創建一個互斥鎖
int shared_data = 0; // 定義一個共享數據
// 線程函數
void thread_func(int num_iterations) {
for (int i = 0; i < num_iterations; ++i) {
mtx.lock(); // 加鎖
++shared_data; // 修改共享數據
mtx.unlock(); // 解鎖
}
}
int main() {
const int num_threads = 5;
const int iterations_per_thread = 1000;
std::thread threads[num_threads]; // 創建線程數組
// 啟動線程
for (int i = 0; i < num_threads; ++i) {
threads[i] = std::thread(thread_func, iterations_per_thread);
}
// 等待所有線程完成
for (int i = 0; i < num_threads; ++i) {
threads[i].join();
}
std::cout << "Final value of shared_data: " << shared_data << std::endl;
return 0;
}
在這個示例中,我們創建了一個互斥鎖mtx和一個共享數據shared_data。我們創建了5個線程,每個線程執行thread_func函數,該函數對shared_data進行遞增操作。在thread_func中,我們使用mtx.lock()加鎖,然后修改共享數據,最后使用mtx.unlock()解鎖。這樣可以確保在同一時間只有一個線程可以訪問和修改共享數據,從而實現線程同步。