/* std c++ 多线程同步的例子
* 用std::condition_variable 实现的生产者,消费者同步的例子
* 当条件满足了,生产者生产出了产品,消费者再消费数据.
* 消费者要等待,生产者要通知消费者消费.
* 简单就是美!
*/
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
std::queue<int> q; //我们把数据存到队列里,当然不用队列也可以的. 顺便演示一下队列用法
std::mutex mtx; //condition 的使用总是伴随者mutex 锁定
std::condition_variable cond;
void producer() //生产者线程
{
for(int data=0;data<10;data++)
{
std::unique_lock<std::mutex> locker(mtx); //采用unique_lock 锁定mtx
q.push(data);
locker.unlock(); //释放锁
cond.notify_one(); // Notify one waiting thread, if there is one
std::this_thread::sleep_for(std::chrono::seconds(1)); //chrono 计时,是一个命名空间
}
}
void consumer() //消费者线程,接受到数据9就退出
{
int data = 0;
while (data != 9)
{
std::unique_lock<std::mutex> locker(mtx); //采用unique_lock 锁定mtx
while (q.empty())
cond.wait(locker); // Unlock mtx and wait to be notified
data = q.back();
q.pop();
locker.unlock();
std::cout << "t2 got a value from t1: " << data << std::endl;
}
}
int main()
{
std::thread t1(producer); //创建线程对象t1, 以producer 函数为线程
std::thread t2(consumer); //创建线程对象t2, 以consumer 函数为线程
//主线程等待子线程执行完毕
t1.join();
t2.join();
return 0;
}
结果:
./test_thread_cpp
t2 got a value from t1: 0
t2 got a value from t1: 1
t2 got a value from t1: 2
t2 got a value from t1: 3
t2 got a value from t1: 4
t2 got a value from t1: 5
t2 got a value from t1: 6
t2 got a value from t1: 7
t2 got a value from t1: 8
t2 got a value from t1: 9