用C++实现一个并发编程阻塞队列BlockingQueue

用C++实现一个并发编程阻塞队列BlockingQueue

#pragma once
#include 
#include 
#include 

template <typename T>
class BlockingQueue
{
public:
    void add(const T& item)
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_queue.push(item);
        m_condition.notify_one();
    }

    void add(T&& item)
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_queue.push(std::move(item));
        m_condition.notify_one();
    }

    template <class... Args>
    void emplace(Args&&... args)
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_queue.emplace(std::forward<Args>(args)...);
        m_condition.notify_one();
    }

    T take()
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        while (m_queue.empty())
        {
            m_condition.wait(lock);
        }
        T item = m_queue.front();
        m_queue.pop();
        return item;
    }

    size_t size()
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        return m_queue.size();
    }

private:
    std::queue<T>           m_queue;
    std::mutex              m_mutex;
    std::condition_variable m_condition;
};

你可能感兴趣的:(C++,多线程,c++)