[英]blocking queue using c++ std queue
我正在嘗試為一個提供者和多個使用者實現一個有限大小的阻塞隊列。 消費者睡眠1秒鍾時,它工作良好,但沒有睡眠時掛起。 我究竟做錯了什么?
這是我的代碼:
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
using namespace std;
template <class T> class BlockingQueue: public queue<T> {
public:
BlockingQueue() {
queue<T>();
}
BlockingQueue(int size) {
maxSize = size;
queue<T>();
}
void push(T item) {
unique_lock<std::mutex> wlck(writerMutex);
while(Full())
isFull.wait(wlck);
queue<T>::push(item);
if(notEmpty())
isEmpty.notify_one();
}
bool notEmpty() {
return !queue<T>::empty();
}
bool Full(){
return queue<T>::size() >= maxSize;
}
T pop() {
unique_lock<std::mutex> lck(readerMutex);
popMutex.lock();
while(queue<T>::empty()) {
isEmpty.wait(lck);
}
T value = queue<T>::front();
queue<T>::pop();
if(!Full())
isFull.notify_all();
popMutex.unlock();
return value;
}
private:
int maxSize;
std::mutex readerMutex;
std::mutex popMutex;
std::mutex writerMutex;
condition_variable isFull;
condition_variable isEmpty;
};
void runProvider(BlockingQueue<int>* Q) {
int number=0;
while(1) {
Q->push(number);
cout<<"provide "<<number<<endl;
number++;
}
}
void runConsumer(int n,BlockingQueue<int>* Q) {
int number;
while(1) {
number = Q->pop();
cout<<"consume#"<<n<<": "<<number<<endl;
}
}
int main(int argc, char** argv) {
BlockingQueue<int> *Queue = new BlockingQueue<int>(10);
cout<<"starting provider"<<endl;
std:thread provider(runProvider, Queue);
sleep(1);
cout<<"starting consumer"<<endl;
std::thread consumer1(runConsumer, 1,Queue);
std::thread consumer2(runConsumer, 2,Queue);
provider.join();
delete(Queue);
return 0;
}
這是我的固定代碼,用於阻止具有多個提供者和多個使用者且隊列大小受限的隊列:
template <class T> class BlockingQueue: public queue<T> {
public:
BlockingQueue(int size) {
maxSize = size;
}
void push(T item) {
unique_lock<std::mutex> wlck(writerMutex);
while(Full())
isFull.wait(wlck);
queue<T>::push(item);
isEmpty.notify_all();
}
bool notEmpty() {
return !queue<T>::empty();
}
bool Full(){
return queue<T>::size() >= maxSize;
}
T pop() {
unique_lock<std::mutex> lck(readerMutex);
while(queue<T>::empty()) {
isEmpty.wait(lck);
}
T value = queue<T>::front();
queue<T>::pop();
if(!Full())
isFull.notify_all();
return value;
}
private:
int maxSize;
std::mutex readerMutex;
std::mutex writerMutex;
condition_variable isFull;
condition_variable isEmpty;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.