#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <thread>
#include <string>
#include <mutex>
#include <fstream>
#include <deque>
#include <condition_variable>
using namespace std;
deque<int> q;
mutex mu; //互斥对象mu
condition_variable cond; //条件变量可以避免线程2许多无谓的循环,换句话说,可以部分控制线程间的访问循序
void function_1(){
int count = 10;
while (count>0){
unique_lock<mutex> locker(mu);
q.push_front(count);
locker.unlock();
cond.notify_one(); //激活一个等待这个条件的线程;如果有多个线程再等待,改用notify_all()
this_thread::sleep_for(chrono::seconds(1));
count--;
}
}
void function_2(){
int date = 0;
while (date != 1){
unique_lock<mutex> locker(mu);
cond.wait(locker, [](){return !q.empty(); }); //将线程2休眠,直到线程1调用cond.notify_one(); 第二个参数防止伪激活,就是说只有q不为空时,激活才有效
if (!q.empty()){
date = q.back();
q.pop_back();
locker.unlock();
cout << "t2 got a value from t1: " << date << endl;
}
}
}
int _tmain(int argc, _TCHAR* argv[]){
thread t1(function_1);
thread t2(function_2);
t1.join();
t2.join();
system("PAUSE");
return 0;
}
在本例中,function_1函数中产生队列q的数据,function_2函数中消耗队列q的数据。通过添加条件变量cond,控制了线程间的部分访问循序,并且阻止了线程2 的无谓循环