在t1线程中插入值,在t2线程中取出值。
#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <mutex>
#include <deque>
using namespace std;
std::deque<int> q;
mutex mu;
void fun2()
{
int count =10;
while(count >0)
{
std::unique_lock<mutex> locker(mu);
q.push_front(count);
cout<<"t1 put valut into deque:"<<count<<endl;
locker.unlock();
std::this_thread::sleep_for(chrono::seconds(1));
count--;
}
}
void fun3()
{
int data =0;
while(data !=1)
{
std::unique_lock<mutex> locker(mu);
if(!q.empty()){
data = q.back();
q.pop_back();
locker.unlock();
cout<<"t2 got a value from t1:"<<data<<endl;
}else{
locker.unlock();
}
}
}
int main()
{
thread t1(fun2);
thread t2(fun3);
t1.join();
t2.join();
return 0;
}
use condition_variable
#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <mutex>
#include <deque>
#include <condition_variable>
using namespace std;
std::deque<int> q;
mutex mu;
condition_variable cond;
void fun2()
{
int count =10;
while(count >0)
{
std::unique_lock<mutex> locker(mu);
q.push_front(count);
cout<<"t1 put valut into deque:"<<count<<endl;
locker.unlock();
cond.notify_one();
//cond.notify_all();
std::this_thread::sleep_for(chrono::seconds(1));
count--;
}
}
void fun3()
{
int data =0;
while(data !=1)
{
std::unique_lock<mutex> locker(mu);
cond.wait(locker,[](){return !q.empty();});
data = q.back();
q.pop_back();
locker.unlock();
cout<<"t2 got a value from t1:"<<data<<endl;
}
}
int main()
{
thread t1(fun2);
thread t2(fun3);
t1.join();
t2.join();
return 0;
}