1 例子
多線程訪問同一資源時,為了保證數據的一致性,必要時需要加鎖。
1.1 直接操作 mutex,即直接調用 mutex 的 lock / unlock 函數。
#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 == " << i << std::endl;
// 前面代碼如有異常,unlock 就調不到了。
mutex.unlock();
}
int main() {
boost::thread_group threads;
for (int i = 0; i < 4; ++i) {
threads.create_thread(&Counter);
}
threads.join_all();
return 0;
}
1.2 使用 lock_guard 自動加鎖、解鎖。原理是 RAII,和智能指針類似。
#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;
}
1.3 使用 unique_lock 自動加鎖、解鎖。
unique_lock 與 lock_guard 原理相同,但是提供了更多功能(比如可以結合條件變量使用)。
注意:mutex::scoped_lock 其實就是 unique_lock
#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;
}
2 unique_lock和lock_guard的區別
簡單的說,unique_lock相對於lock_guard,會有更多特性。
unique_lock和lock_guard都遵循RAII。
unique_lock和lock_guard最大的不同是unique_lock不需要始終擁有關聯的mutex,而lock_guard始終擁有mutex。這意味着unique_lock需要利用owns_lock()判斷是否擁有mutex。另外,如果要結合使用條件變量,應該使用unique_lock。
-
Lock doesn't have to taken right at the construction, you can pass the flag std::defer_lock during its construction to keep the mutex unlocked during construction.
-
We can unlock it before the function ends and don't have to necessarily wait for destructor to release it, which can be handy.
-
You can pass the ownership of the lock from a function, it is movable and not copyable.
-
It can be used with conditional variables since that requires mutex to be locked, condition checked and unlocked while waiting for a condition.
參考[StackOverflow]:https://stackoverflow.com/questions/6731027/boostunique-lock-vs-boostlock-guard
