BlockingQueue阻塞队列

📅 2026/7/1 4:16:15
BlockingQueue阻塞队列
#include iostream #include queue #include thread #include mutex #include condition_variable using namespace std; template typename T class BoundedBlockingQueue { public: // capacity: 队列最大容量 explicit BoundedBlockingQueue(int capacity) : capacity_(capacity) {} // 入队如果队列已满则阻塞直到有空位 void enqueue(T element) { std::unique_lockstd::mutex lock(mtx_); not_full_.wait(lock, [this]() { return queue_.size() capacity_; }); queue_.push(std::move(element)); not_empty_.notify_one(); } // 出队如果队列为空则阻塞直到有元素 T dequeue() { std::unique_lockstd::mutex lock(mtx_); not_empty_.wait(lock, [this]() { return !queue_.empty(); }); T element std::move(queue_.front()); queue_.pop(); not_full_.notify_one(); return element; } // 查询当前元素个数非阻塞 size_t size() const { std::lock_guardstd::mutex lock(mtx_); return queue_.size(); } // 查询最大容量 size_t capacity() const { return capacity_; } private: const size_t capacity_; std::queueT queue_; mutable std::mutex mtx_; std::condition_variable not_full_; std::condition_variable not_empty_; }; int main() { BoundedBlockingQueueint q(5); // 容量为 5 //std::thread producer([]() { for (int i 0; i 10; i) { q.enqueue(i); std::cout enqueue i std::endl; }; // }); std::thread consumer([]() { for (int i 0; i 10; i) { int val q.dequeue(); std::cout dequeue val std::endl; } }); //producer.join(); consumer.join(); }