单生产者单消费者模式,假设生产者每次产量等于与消费者每次消耗量
C++ 11 使用unique_lock 和 condition_variable 实现
//#include "stdafx.h"
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
//单生产者单消费者模式,假设生产者每次产量等于与消费者每次消耗量
class Repository {
public:
Repository(const int sz = 9) : circularBuffer(sz) {} //仓库容量大小为sz
Repository(const Repository& other) = delete;
Repository operator=(const Repository& other) = delete;
~Repository() {}
void producer() {
cout << " producer thread id:" << std::this_thread::get_id() << endl;
for (int i = 0; i < capacity; ++i) {
std::unique_lock<std::mutex> smartLock(mtx);
//可用量小于仓库容量,尝试获取锁,然后生产
buffNotFull.wait(smartLock, [this] {return bufferd < circularBuffer.size(); });
circularBuffer[proPosnMark] = i;
proPosnMark = (proPosnMark + 1) % circularBuffer.size();
++bufferd;
cout << "producer input:" << i << endl;
smartLock.unlock(); //解锁
buffNotEmpty.notify_all(); //通知消费者
}
return;
}
void consumer() {
cout << "consumer thread id:" << std::this_thread::get_id() << endl;
for (int i = 0; i < capacity; ++i) {
std::unique_lock<std::mutex> smartLock(mtx);
buffNotEmpty.wait(smartLock, [this] {return bufferd > 0;});
int val = circularBuffer[conPosnMark];
cout << " consumer delete:" << val << endl;
conPosnMark = (conPosnMark + 1) % circularBuffer.size();
--bufferd;
smartLock.unlock();
buffNotFull.notify_all();
}
return;
}
private:
std::vector<int> circularBuffer; //环形仓库
size_t bufferd = 0; //仓库内可用产品
size_t proPosnMark = 0; //生产者位置标记
size_t conPosnMark = 0; //消费者位置标记
int capacity = 100; //生产总量
std::mutex mtx;
std::condition_variable buffNotEmpty; //仓库未空
std::condition_variable buffNotFull; //仓库未满
};
int main(int argc, char *argv[])
{
cout << "main thread id:" << std::this_thread::get_id() << endl;
Repository mRep;
std::vector<std::thread> vThreads;
vThreads.push_back(std::thread(&Repository::producer, &mRep));
vThreads.push_back(std::thread(&Repository::consumer, &mRep));
for (auto &elem : vThreads) {
elem.join();
}
system("pause");
return 0;
}
//关于condition_variable
//condition_variable.wait()第二参数(谓词)。
//不带谓词,线程直接被block,等待被唤醒,被唤醒后,尝试获取锁。
//带有谓词,返回false,解锁, 线程被block,等待被唤醒,返回ture, 尝试获取锁,获取后,线程往下走。
enjoy;