2022-05-17 惊呆了,居然发现还有人还不会写线程安全的队列~


前言

工作中,居然发现还有人不会写线程安全的队列,额,这就有点过分了。利用早上泡茶的时间,手写了几行代码,实现了基本的入队、出队操作。
可以拿来直接用。


言归正传

  • 上代码
/*
	FileName: Threadsafe_queue.h
*/


#pragma once

//肯定基于容器queue、条件变量、互斥量
#include <queue>
#include <mutex>
#include <condition_variable>


//模板编程
template <typename T>
class Threadsafe_queue
{
public:
	
	
	//入队
	void Push(T value) 
	{
		std::unique_lock<std::mutex> lk(m_mutex);
		m_queue.push(value);
		m_cond.notify_one();
	}

	//等待,直到有数据,然后出队
	void Wait_for_pop(T& value)
	{
		std::unique_lock<std::mutex> lk(m_mutex);
		m_cond.wait(lk, [this]
			{
				return !m_queue.empty();
			});
		value = m_queue.front();
		m_queue.pop();
	}

	//尝试出队
	bool Try_pop(T& value)
	{
		//与前面不同的是,不需要阻塞wait
		std::lock_guard<std::mutex> lk(m_mutex);
		if (m_queue.empty())
			return false;
		value = m_queue.front();
		m_queue.pop();
		return true;
	}

	//判断是否为空
	bool IsEmpty() const
	{
		std::lock_guard<std::mutex> lk(m_mutex);
		return m_queue.empty();
	}
private:
	std::mutex m_mutex;
	std::condition_variable m_cond;
	std::queue<T> m_queue;
};
  • 上demo
/*
	FileName: main.cpp
*/


#include <iostream>
#include "Threadsafe_queue.h"

Threadsafe_queue<int> gSafethread_queue;

int Threadfun1()
{
    //阻塞等待,有数据就处理,CPU占用很低
    int value = 0;
    while (true)
    {
        std::cout << "wait data\n";
        gSafethread_queue.Wait_for_pop(value);
        std::cout << "get data = " << value << std::endl;
    }
   
}

int Threadfun2()
{
    //try_pop是立即返回,CPU占满
    int value = 0;
    while (true)
    {
        std::cout << "try data\n";
        gSafethread_queue.Try_pop(value);
        std::cout << "try data = " << value << std::endl;
    }

}


int Threadfun3()
{
    //生产者线程
    while (true)
    {
        
        gSafethread_queue.Push(rand()%  100);
        std::this_thread::sleep_for(std::chrono::seconds(1));
        
    }

}

int main()
{
    std::cout << "Hello World!\n";


    std::thread m_thread1(Threadfun1);      //阻塞等
    //std::thread m_thread2(Threadfun2);      
    std::thread m_thread3(Threadfun3);
    getchar();
    
}

跑一跑

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShaYQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值