#include<iostream>
#include<deque>
#include<thread>
#include<mutex>
#include<pthread.h>
std::deque<int> q;//先進先出
std::mutex mu;
void function_1()//生產着
{
int count=10;
while(count>0)
{
std::unique_lock<std::mutex> locker(mu);
q.push_front(count);
locker.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));//延時1s
count--;
}
}
void function_2()//消費者
{
int data=0;
while(data!=1)
{
std::unique_lock<std::mutex> locker(mu);
if(!q.empty())
{
data=q.back();
q.pop_back();
locker.unlock();
std::cout<<"t2 got a value from t1:"<<data<<std::endl;
}
else
{
locker.unlock();
}
}
}
int main()
{
std::thread t1(function_1);
std::thread t2(function_2);
t1.join();
t2.join();
return 0;
}
程序運行步驟是這樣的:
1.首先同時運行t1線程和t2線程
2.先進入t1線程的function_1()函數,這個時候加了mymutex鎖,另外一個t2線程進入後發現mymutex鎖沒有釋放,只能等待。
3.當過去10個循環(每個循環1秒後)t1線程結束,unique_lock lock(mymutex)的生命週期結束,mymutex鎖釋放,執行t2線程,此時開始一直讀取。
關於此文件的CMakeLists.txt文件編寫
cmake_minimum_required(VERSION 2.8)
project(test_mutex)
add_compile_options(-std=c++11 -g -Wall)
add_executable(test_mutex test_mutex.cpp)
target_link_libraries(test_mutex pthread)
必須要鏈接到pthread線程庫,否則編譯出錯。