C/C++ 线程安全队列

一些相关的理论暂未查到,简单做个记录

#include 
#include "mutex"
#include "condition_variable"
#include "queue"
#include "thread"
#include "chrono"
template
class ThreadSafeQueue
{
private:
    mutable std::mutex m_mutex;
    std::queue m_queue;
    std::condition_variable m_cond;
public:
    ThreadSafeQueue()
    {
    }

    ThreadSafeQueue(const ThreadSafeQueue&)=delete;
    void push(T data)
    {
        std::lock_guard lock(m_mutex);
        m_queue.push(data);
        m_cond.notify_one();
    }

    void WaitPop(T& t)
    {
        std::unique_lock lock(m_mutex);
        m_cond.wait(lock,[this]{return !m_queue.empty();});
        t=m_queue.front();
        m_queue.pop();
    }

    std::shared_ptr WaitPop()
    {
        std::unique_lock lock(m_mutex);
        m_cond.wait(lock,[this]{return !m_queue.empty();});
        std::shared_ptr res(std::make_shared(m_queue.front()));
        m_queue.pop();
        return res;

    }

    bool TryPop(T& t)
    {
        std::lock_guard lock(m_mutex);
        if(m_queue.empty())
        {
            return false;
        }

        t=m_queue.front();
        m_queue.pop();
        return true;
    }

    std::shared_ptr TryPop()
    {
        std::lock_guard lock(m_mutex);
        if(m_queue.empty())
        {
            return std::shared_ptr();
        }

        std::shared_ptr res(std::make_shared(m_queue.front()));
        m_queue.pop();

        return  res;
    }

    bool IsEmpty()
    {
        std::lock_guardlock(m_mutex);
        return m_queue.empty();
    }
};

ThreadSafeQueue g_queue;
int g_index=10;

void threadFunc_1()
{
    std::cout << "threadFunc_1 start" << std::endl;
    while (true)
    {
        int value=0;
        g_queue.WaitPop(value);
        printf("wait_and_pop done! value=%d thread id:%d\n",value,std::this_thread::get_id());
    }
}

void threadFunc_2()
{
    std::cout<<"threaFunc_2 start"<

运行结果:

C/C++ 线程安全队列_第1张图片

参考:

https://blog.csdn.net/what951006/article/details/77916490 代码参考

https://blog.csdn.net/qq_34199383/article/details/79990986?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control   atomic的详细讲解

https://zhuanlan.zhihu.com/p/355113813 线程安全队列--生产者与消费者模型

https://blog.csdn.net/wanggao_1990/article/details/103584882#commentBox 对一些实现情形进行了简要说明(推荐看一下)

 

  

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