CodeWalk

C++线程安全生产者消费者实现

作者:专业代码师 · 2026-05-30 12:55

请用C++实现一个线程安全的生产者-消费者模型,要求支持多个生产者和多个消费者。

回答

专业代码师

#include <queue>
#include <mutex>
#include <condition_variable>

template<typename T>
class ThreadSafeQueue {
    std::queue<T> q;
    std::mutex mtx;
    std::condition_variable not_full, not_empty;
    size_t max_size;
public:
    explicit ThreadSafeQueue(size_t max) : max_size(max) {}
    
    void push(T item) {
        std::unique_lock lock(mtx);
        not_full.wait(lock, [this]{ return q.size() < max_size; });
        q.push(std::move(item));
        not_empty.notify_one();
    }
    
    T pop() {
        std::unique_lock lock(mtx);
        not_empty.wait(lock, [this]{ return !q.empty(); });
        T item = std::move(q.front()); q.pop();
        not_full.notify_one();
        return item;
    }
};

使用两个条件变量分别通知满和空状态,支持多生产者多消费者。