C++双缓冲队列实现

#pragma once

#include <queue>
#include <mutex>

namespace Infra {
    
    
    template<class T>
    class DoubleQueue {
    
    
    public:
        explicit DoubleQueue(int max_capacity)
            : max_capacity_(max_capacity) {
    
    }

        void push(T& ptr) {
    
    
            std::lock_guard<std::mutex> lock(swap_mutex_);
            if (write_queue_.size() > max_capacity_) {
    
    
                std::cout << "write_queue_ overflow!!!" << std::endl;
                return ;
            }
            write_queue_.emplace(ptr);
        }

        T pop() {
    
    
            if (read_queue_.empty()) {
    
    
                std::lock_guard<std::mutex> lock(swap_mutex_);
                if (write_queue_.empty()) {
    
    
                    return nullptr;
                }
                read_queue_.swap(write_queue_);
            }
            auto ptr = read_queue_.front();
            read_queue_.pop();
            return ptr;
        }

    private:
        int max_capacity_;
        std::queue<T>  write_queue_;
        std::queue<T>  read_queue_;
        std::mutex swap_mutex_;
    };
}

猜你喜欢

转载自blog.csdn.net/tech2ipo/article/details/90513803