17370845950

c++中如何实现一个线程安全队列_c++中线程安全队列实现方法与示例
线程安全队列通过互斥锁和条件变量实现,保证多线程环境下数据一致性。使用std::mutex保护共享队列,std::condition_variable实现线程间通信,push操作入队后唤醒等待线程,wait_and_pop阻塞等待非空,try_pop提供非阻塞尝试,支持多生产者多消费者场景,避免竞争与忙等待,确保高效同步。

在C++中实现一个线程安全队列,核心是保护共享数据不被多个线程同时访问导致竞争。通常使用互斥锁(std::mutex)配合条件变量(std::condition_variable)来实现高效的阻塞式队列。这种方式既能保证线程安全,又能避免忙等待。

基本设计思路

线程安全队列需要满足以下几点:

  • 对队列的入队(push)和出队(pop)操作加锁,防止数据竞争
  • 使用条件变量通知等待的线程,有新元素入队
  • 支持多生产者、多消费者场景
  • 避免死锁,锁的粒度要合理

实现代码示例

#include 
#include 
#include 
#include 
#include 

template
class ThreadSafeQueue {
private:
    std::queue data_queue;
    mutable std::mutex mtx;
    std::condition_variable cv;

public:
    ThreadSafeQueue() = default;

    void push(T value) {
        std::lock_guard lock(mtx);
        data_queue.push(std::move(value));
        cv.notify_one(); // 唤醒一个等待的消费者
    }

    bool try_pop(T& value) {
        std::lock_guard lock(mtx);
        if (data_queue.empty()) {
            return false;
        }
        value = std::move(data_queue.front());
        data_queue.pop();
        return true;
    }

    void wait_and_pop(T& value) {
        std::unique_lock lock(mtx);
        cv.wait(lock, [this] { return !data_queue.empty(); });
        value = std::move(data_queue.front());
        data_queue.pop();
    }

    bool empty() const {
        std::lock_guard lock(mtx);
        return data_queue.empty();
    }

    size_t size() const {
        std::lock_guard lock(mtx);
        return data_queue.size();
    }
};

使用示例:生产者-消费者模型

void producer(ThreadSafeQueue& queue) {
    for (int i = 0; i < 5; ++i) {
        queue.push(i);
        std::cout << "Produced: " << i << "\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

void consumer(ThreadSafeQueue& queue) {
    for (int i = 0; i < 5; ++i) {
        int value;
        queue.wait_and_pop(value);
        std::cout << "Consumed: " << value << "\n";
    }
}

int main() {
    ThreadSafeQueue queue;

    std::thread p1(producer, std::ref(queue));
    std::thread c1(consumer, std::ref(queue));

    p1.join();
    c1.join();

    return 0;
}

该程序输出类似:

Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
...

关键点说明

push() 中使用 notify_one() 及时唤醒一个等待线程,避免消费者长时间挂起。

wait_and_pop() 使用 unique_lock 配合条件变量,能够在队列为空时自动阻塞,直到有数据可用。

try_pop() 提供非阻塞方式获取元素,适用于需要轮询但不想阻塞的场景。

所有公共方法都通过锁保护内部队列,确保任意时刻只有一个线程能修改或读取数据。

基本上就这些。这个实现简单、高效,适合大多数多线程应用场景。