Message Queue c++ 11

#include <iostream>

#include <vector>

#include <condition_variable>

#include <mutex>

#include <thread>

template <typename T>

class MessageQueue {

private:

    std::mutex mu_;

    std::condition_variable cv_;

     std::vector<T> queue_;

 public:

    MessageQueue() {}

    ~MessageQueue(){}

    T get() {

            std::unique_lock<std::mutex> lk(mu_);

            while(queue_.empty())   

                 cv_.wait_for(lk,std::chrono::seconds(1));

            T tt = queue_.front();

            queue_.erase(queue_.begin());

    }

    void put(T& t) {

        std::unique_lock<std::mutex> lk(mu_);

        queue_.push_back(t);

        cv_.notify_one();

    }

};

class Worker {

public:

    Worker() {}

    ~Worker() {}

    void work(MessageQueue<int> *q) {

        for(;;) {

            int j = -1;

             j = q->get();

            std::cout << "thread is " << std::this_thread::get_id() << std::endl;

             std::cout << "j is " << j << std::endl;

        }

      }

};

int main(int argc,char** argv)

{

    const int THREAD_NUM = 3;

    Worker worker;

    MessageQueue<int> mq;

     std::thread threads[THREAD_NUM];

    int i = 100; 

    while( i > 0) {

        mq.put(i);

        i--;

     }

    for(int i = 0; i < THREAD_NUM; i++) 

        threads[i] = std::thread(&Worker::work,&worker,&mq);

    for(int i = 0; i < THREAD_NUM; i++)

        threads[i].join();

    return 0;

}

猜你喜欢

转载自blog.csdn.net/slwrq/article/details/79411981
今日推荐