基于boost库的线程安全queue

STL的queue多线程下是不安全的,当然网上有很多无锁队列,如boost::lockfree::queue就是很好的东西。这里实现一个互斥锁的线程安全队列,基于STL的QUEUE。

/************************************************************************************************
	File Name	:	thread_safe_queue.hpp
	Version		: 	Initial Draft
	Author		:	yang yang
	Created		:	2017.06.08
	Last Modified:	2017.06.08
	Description	:	A thread safe queue,use the queue of STL,and Boost.
************************************************************************************************/

#ifndef THREAD_SAFE_QUEUE_HPP
#define THREAD_SAFE_QUEUE_HPP

#include 
#include 
#include 

template  class ThreadSafeQueue
{
    private:
        std::queue queue;
        boost::mutex mutex;
    public:
        ThreadSafeQueue(){};
        ThreadSafeQueue(const ThreadSafeQueue &other)
        {
            boost::mutex::scoped_lock lock(other.mutex);
            queue = other.queue;
        }
        ~ThreadSafeQueue(){};

        void Push(T &new_value)
        {
            boost::mutex::scoped_lock lock(mutex);
            queue.push(new_value);
            condition.notify_one();
        }
        void Pop(T &value)
        {
            boost::mutex::scoped_lock lock(mutex);
            value = queue.front();
            queue.pop();
        }

        bool TryPop(T &value)
        {
            boost::mutex::scoped_lock lock(mutex);
            if( queue.empty())
            {
                return false;
            }
            else
            {
                value = queue.front();
                queue.pop();
                return true;
            }
        }
        
        bool Empty()
        {
            boost::mutex::scoped_lock lock(mutex);
            return queue.empty();
        }
};

#endif


你可能感兴趣的:(c/c++)