使用c ++ std队列阻塞队列

时间:2016-10-15 23:31:52

标签: c++ multithreading

我试图为一个提供商和多个消费者实施一个有限大小的阻止队列。当消费者睡眠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;
    }

1 个答案:

答案 0 :(得分:0)

以下是我的固定代码,用于阻止具有多个提供程序和多个使用者以及有限队列大小的队列:

std::pair<std::string const, std::string>