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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?