zoukankan      html  css  js  c++  java
  • C++实现安全队列

    ```cpp
    
    #ifndef SAFEQUEUE
    #define SAFEQUEUE
    
    #include <iostream>
    #include <queue>
    #include <thread>
    #include <mutex>
    #include <condition_variable>
    
    using namespace std;
    
    template<typename T>
    class SafeQueue {
    public:
        SafeQueue() {}
    
        ~SafeQueue() {}
    
        void InitQueue()
        {
            work = 1;
        }
    
    
        void EnQueue(T value) 
        {
            lock_guard<mutex> lock(mt);
            if (work) {
                q.push(value);
                cv.notify_one();
            }
        }
    
        void Print()
        {
            lock_guard<mutex> lock(mt);
            queue<T> copy_queue = q;
    
            while (!q.empty())
            {
                copy_queue.push(q.front());
                q.pop();
            }
            while (!copy_queue.empty())
            {
                std::cout << copy_queue.front() << std::endl;
                copy_queue.pop();
            }
        }
    
        int DeQueue(T& value) 
        {
            int ret = 0;
            //占用空间相对lock_guard 更大一点且相对更慢一点,但是配合条件必须使用它,更灵活
            unique_lock<mutex> lock(mt);
            //第二个参数 lambda表达式:false则不阻塞 往下走
            cv.wait(lock, [this] {return !work || !q.empty(); });
            if (!q.empty()) {
                value = q.front();
                q.pop();
                ret = 1;
            }
    
            return ret;
        }
    
        void setWork(int work) 
        {
            lock_guard<mutex> lock(mt);
            this->work = work;
        }
    
        void Clear() 
        {
            lock_guard<mutex> lock(mt);
            while (!q.empty())
            {
                q.pop();
            }
        }
    
        int Find(T value)
        {
            return nullptr;
        }
    
    private:
        mutex mt;
        condition_variable cv;
    
        queue<T> q;
        //是否工作的标记 1 :工作 0:不接受数据 不工作
        int work;
    };
    
    #endif //SAFEQUEUE
    
  • 相关阅读:
    PHP数组函数
    sublime常用快捷键
    PHP中array_merge函数与array+array的区别
    【转】2017PHP程序员的进阶之路
    phpmyadmin上传sql文件大小限制问题解决方案
    二. python的os模块
    一. python的collections模块
    一. python进阶(文件的读写编码)
    七. python进阶(内置函数和高阶函数)
    六. python进阶(递归)
  • 原文地址:https://www.cnblogs.com/liutongqing/p/13597601.html
Copyright © 2011-2022 走看看