How do I implement a thread-safe queue?

In C++, a thread-safe queue can be implemented using mutexes and condition variables to ensure that access to the queue is synchronized among multiple threads. This way, multiple threads can safely enqueue and dequeue items without causing data corruption or inconsistent states.

Below is an example implementation of a thread-safe queue using C++:

#include #include #include #include #include template class ThreadSafeQueue { public: void push(T value) { std::lock_guard<:mutex> lock(mutex_); queue_.push(value); condition_.notify_one(); // Notify one waiting thread } void pop(T& value) { std::unique_lock<:mutex> lock(mutex_); condition_.wait(lock, [&] { return !queue_.empty(); }); // Wait until the queue is not empty value = queue_.front(); queue_.pop(); } bool empty() { std::lock_guard<:mutex> lock(mutex_); return queue_.empty(); } private: std::queue queue_; mutable std::mutex mutex_; std::condition_variable condition_; }; // Example usage void producer(ThreadSafeQueue& queue) { for (int i = 0; i < 10; ++i) { queue.push(i); std::cout << "Produced: " << i << std::endl; } } void consumer(ThreadSafeQueue& queue) { for (int i = 0; i < 10; ++i) { int value; queue.pop(value); std::cout << "Consumed: " << value << std::endl; } } int main() { ThreadSafeQueue queue; std::thread prod(producer, std::ref(queue)); std::thread cons(consumer, std::ref(queue)); prod.join(); cons.join(); return 0; }

thread-safe queue C++ threads mutex condition variable concurrent programming