正確使用std::mutex和std::lock_guard是C++多線程同步的基礎,通過RAII機制避免死鎖,確保共享數(shù)據(jù)安全。
在C++多線程編程中,std::mutex 是最常用的同步機制之一,用于保護共享數(shù)據(jù),防止多個線程同時訪問造成數(shù)據(jù)競爭。正確使用互斥鎖是編寫安全多線程程序的基礎。
使用互斥鎖前,需要包含 <mutex> 頭文件,并定義一個 std::mutex 對象:
#include <iostream> #include <thread> #include <mutex> std::mutex mtx; // 全局互斥鎖 int shared_data = 0;
這個互斥鎖可以是全局變量、類成員變量,或局部靜態(tài)變量,取決于共享數(shù)據(jù)的范圍。
最基本的用法是在線程函數(shù)中調用 lock() 加鎖,操作完共享資源后調用 unlock() 解鎖:
立即學習“C++免費學習筆記(深入)”;
void unsafe_increment() { mtx.lock(); // 加鎖 ++shared_data; // 操作共享數(shù)據(jù) std::cout << "Value: " << shared_data << "\n"; mtx.unlock(); // 解鎖 }
這種方式容易出錯,比如忘記 unlock() 或者在 unlock 前發(fā)生異常,會導致死鎖。因此不推薦直接使用。
std::lock_guard 是RAII(資源獲取即初始化)風格的鎖管理類,構造時自動加鎖,析構時自動解鎖:
void safe_increment() { std::lock_guard<std::mutex> guard(mtx); ++shared_data; std::cout << "Value: " << shared_data << "\n"; // 離開作用域時自動釋放鎖 }
如果需要延遲加鎖、條件變量配合或手動控制解鎖時機,可以使用 std::unique_lock:
std::unique_lock<std::mutex> ulock(mtx, std::defer_lock); // do something else... ulock.lock(); // 手動加鎖 // 操作共享資源 ulock.unlock(); // 可提前釋放 // 其他操作... // 析構時仍會檢查是否已解鎖
下面是一個完整的例子,創(chuàng)建多個線程安全地遞增共享變量:
#include <iostream> #include <thread> #include <mutex> #include <vector> std::mutex mtx; int counter = 0; void worker(int id) { for (int i = 0; i < 1000; ++i) { std::lock_guard<std::mutex> guard(mtx); ++counter; } } int main() { std::vector<std::thread> threads; for (int i = 0; i < 10; ++i) { threads.emplace_back(worker, i); } for (auto& t : threads) { t.join(); } std::cout << "Final counter value: " << counter << "\n"; return 0; }
輸出結果始終為 10000,說明互斥鎖有效防止了數(shù)據(jù)競爭。
基本上就這些。掌握 mutex 和 lock_guard 的組合使用,就能應對大多數(shù)多線程同步場景。關鍵是避免裸調用 lock/unlock,優(yōu)先使用 RAII 封裝,確保程序健壯性。
以上就是c++++中mutex(互斥鎖)怎么使用_c++多線程互斥鎖用法詳解的詳細內容,更多請關注php中文網(wǎng)其它相關文章!
c++怎么學習?c++怎么入門?c++在哪學?c++怎么學才快?不用擔心,這里為大家提供了c++速學教程(入門到精通),有需要的小伙伴保存下載就能學習啦!
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號