#include <iostream>
using namespace std;
#include <list>
#include <thread>
#include <mutex>
class A
{
public:
std::unique_lock<std::mutex> rtn_unique_lock()
{
unique_lock<std::mutex> tmpguard(my_mutex);
return tmpguard;
}
void receiveMes()
{
for (int i = 0; i < 10000; ++i)
{
//std::lock_guard<std::mutex> sbguard(my_mutex, std::adopt_lock);
//std::unique_lock<std::mutex> sbguard(my_mutex, std::adopt_lock);
//上述兩種方法相似,默認在尾部析構函數中釋放mutex
std::unique_lock<std::mutex> sbguard (my_mutex, std::try_to_lock);
//嘗試去鎖定mutex,不會卡在這里不動
//std::unique_lock<std::mutex> sbguard(my_mutex, std::defer_lock);
//defer_lock是初始化一個沒有加鎖的mutex,其中的幾個關鍵成員函數: lock(), unlock(), try_lock(),release();
//lock() 加鎖
//unlock() 釋放鎖
//try_lock() 嘗試加鎖,如果成功則返回true,否則false
//release() 返回它所管理的mutex對象指針,釋放所有權,也就是 說這個unique_lock和mutex沒有關系 mutex *Pmutex = sbguard.release()
//鎖住的代碼的多少稱為粒度
//sbguard 和 mutex之間的關系只能是一對一的關系,需要使用move函數,轉移所有權
//std::unique_lock<std::mutex> sbguard1 (std::move(sbguard));
//或者:見上面的rtn_unique_lock()函數,返回一個局部變量會導致系統生成一個臨時unique_lock對象,並調用unique_lock的移動構造函數
if (sbguard.owns_lock())
{
msgQueue.push_back(i);
cout << "msgQueue insert " << i << endl;
}
else
{
cout << "do some other thing" << endl;
}
}
}
void dealMsg()
{
for (int i = 0; i < 10000; ++i)
{
my_mutex.lock();
std::chrono::milliseconds dura(20000);
this_thread::sleep_for(dura);
if (!msgQueue.empty())
{
int command = msgQueue.front();
cout << "deal msgQueue" << command << endl;
msgQueue.pop_front();
}
my_mutex.unlock();
}
}
private:
list<int> msgQueue;
mutex my_mutex; //互斥量
};
int main()
{
A myobj;
thread threadReceive(&A::receiveMes, &myobj); //傳入的對象要進行數據處理,所以傳入引用。
thread threadDeal(&A::dealMsg, &myobj);
threadReceive.join();
threadDeal.join();
return 0;
}