• C++实现简单的线程安全队列


    /*
    实现一个线程安全的队列
    */
    
    template <class T>
    class SafeQueue
    {
    public:
        SafeQueue(void):q(),m(),c()
        {}
        ~SafeQueue(void)
        {}
        // Add an element to the queue.
        void enqueue(T t)
        {
            std::lock_guard<std::mutex> lock(m);
            q.push(t);
            c.notify_one();
        }
    
        // Get the "front"-element.
       // If the queue is empty, wait till a element is avaiable.
        T dequeue(void)
        {
            std::unique_lock<std::mutex> lock(m);
            while (q.empty())
            {
                // release lock as long as the wait and reaquire it afterwards.
                c.wait(lock);
            }
            T val = q.front();
            q.pop();
            return val;
        }
    
    
    private:
        std::queue<T> q;
        mutable std::mutex m;
        std::condition_variable c;
    };
  • 相关阅读:
    Python Day7(相关补充)
    Python Day7
    Python Day6
    Python Day5
    Python Day4
    Python Day3
    Python Day2
    Python Day1
    复杂装饰器原理分析
    Unity 坐标
  • 原文地址:https://www.cnblogs.com/LuckCoder/p/14549952.html
Copyright © 2020-2023  润新知