#include <queue>
#include <thread>
#include <mutex>
#include <iostream>
#include <vector>
#include <unistd.h>
std::queue<std::string> mQueue;
std::mutex m;
std::condition_variable cv_notEmpty;
void workerPut(int max_num, int interval=1){
for(int i=0;i<max_num;i++){
sleep(interval);
std::unique_lock<std::mutex> lk_queue(m);
mQueue.push("JobItem " + std::to_string(i));
std::cout << "put value to queue: " << i << std::endl;
cv_notEmpty.notify_all();
}
}
void workShow(int interval=2){
while(true){
sleep(interval);
std::unique_lock<std::mutex> lk_queue(m);
cv_notEmpty.wait(lk_queue,[]{return !mQueue.empty();});
std::string value = mQueue.front();
mQueue.pop();
std::cout << "consume value: " + value << std::endl;
}
}
int main(){
std::thread producer(workerPut,10,1);
std::thread consumer(workShow,2);
producer.join();
consumer.join();
return 0;
}
上面有个限制:
(1)生产者生产max_num个产品就退出;
(2)对队列上线没有做要求。
下面继续改进,
(1)生产者可以一直生产产品放到队列;
(2)设置队列最大长度,即队列满了则生产者要被阻塞等待;等待消费者消费了数据,队列有空余,再进行生产;
(3)消费者当队列不空时消费产品
#include <queue>
#include <thread>
#include <mutex>
#include <iostream>
#include <vector>
#include <unistd.h>
std::queue<std::string> mQueue;
std::mutex m;
std::condition_variable cv_notEmpty;
std::condition_variable cv_notFull;
void workerPut(int max_num, int interval=1){
int i = 0;
while(true){
sleep(interval);
std::unique_lock<std::mutex> lk_queue(m);
cv_notFull.wait(lk_queue, []{return mQueue.size()<5;}); // queue最长5
mQueue.push("JobItem " + std::to_string(i));
std::cout << "put value to queue: " << i << std::endl;
std::cout << "current queue is : " << mQueue.size() << std::endl;
cv_notEmpty.notify_all();
i++;
}
}
void workShow(int interval=2){
while(true){
sleep(interval);
std::unique_lock<std::mutex> lk_queue(m);
cv_notEmpty.wait(lk_queue,[]{return !mQueue.empty();});
std::string value = mQueue.front();
mQueue.pop();
std::cout << "consume value: " + value << std::endl;
std::cout << "current queue is : " << mQueue.size() << std::endl;
cv_notFull.notify_all();
}
}
int main(){
std::thread producer(workerPut,10,1);
std::thread consumer(workShow,2);
producer.join();
consumer.join();
return 0;
}
由于设置了队列最长为5,而且生产速度是消费速度的2倍,因此最终队列长度会一直保持在5