C++11Mutex(互斥鎖)詳解

來源:互聯網
上載者:User

標籤:資源   簡單的   加鎖   直接   資料   ++i   reads   cpp   out   

多個線程訪問同一資源時,為了保證資料的一致性,最簡單的方式就是使用 mutex(互斥鎖)。

(1).直接操作 mutex,即直接調用 mutex 的 lock / unlock 函數。此例順帶使用了 boost::thread_group 來建立一組線程。

[cpp] view plain copy
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>

boost::mutex mutex;
int count = 0;

void Counter() {
mutex.lock();

int i = ++count;
std::cout << "count == " www.furggw.com/<< i << std::endl;

// 前面代碼如有異常,unlock 就調不到了。
mutex.unlock();
}

int main() {
// 建立一組線程。
boost::thread_group threads;
for (int i = 0; i www.mcyulegw.com< 4; ++i) {
threads.create_thread(&Counter);
}

// 等待所有線程結束。
threads.join_all();
return 0;
}
(2).使用 lock_guard 自動加鎖、解鎖。原理是 RAII,和智能指標類似

[cpp] view plain copy
#include <iostream>
#include <boost/thread/lock_guard.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>

boost::mutex mutex;
int count = 0;

void Counter() {
// lock_guard 在建構函式裡加鎖,在解構函式裡解鎖。
boost::lock_guard<boost::mutex> lock(mutex);

int i = ++count;
std::cout << "count == " << i << std::endl;
}

int main() {
boost::thread_group threads;
for (int i = 0; i < 4; ++i) {
threads.create_thread(&Counter);
}

threads.join_all();
return 0;
}
(3).使用 unique_lock 自動加鎖、解鎖。
unique_lock 與 lock_guard 原理相同,但是提供了更多功能(比如可以結合條件變數使用)。注意:mutex::scoped_lock 其實就是 unique_lock<mutex> 的 typedef。

[cpp] view plain copy
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>

boost::mutex mutex;
int count = 0;

void Counter() {
boost::unique_lock<boost::mutex> lock(mutex);

int i = ++count;
std::cout << "count == " << i << std::endl;
}

int main() {
boost::thread_group threads;
for (int i = 0; i < 4; ++i) {
threads.create_thread(&Counter);
}

threads.join_all();
return 0;

C++11Mutex(互斥鎖)詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.