

Implement thread-safe queue in C++
source link: https://www.geeksforgeeks.org/implement-thread-safe-queue-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Implement thread-safe queue in C++
What is a Thread-safe Queue?
A thread-safe queue is a data structure that is designed to provide thread safety for a concurrent environment.
It is a data structure that allows multiple threads to access the same queue and enqueue and dequeue elements concurrently. The threads do not need to be synchronized, as the internal structure of the queue makes sure that the threads do not interfere with each other. Thus, it provides a safe and efficient way to access shared resources from multiple threads.
Why should we use Thread-safe Queue?
- Thread-safe queues are commonly used in multi-threaded applications, where multiple threads need to access a shared resource.
- By using a thread-safe queue, the threads can safely access the queue without the need for synchronization.
- This makes it more efficient and less prone to errors.
- Thread-safe queues are also useful for tasks that need to be performed in parallel, as they can be used to distribute tasks among multiple threads.
Implementation:
A thread-safe queue in C++ can be implemented using a mutex along with a standard queue. A mutex is a synchronization object used to protect access to a shared resource, such as a thread-safe queue. The mutex should be locked before pushing or popping elements from the queue and unlocked after the operation is complete. A mutex is used to protect access to the queue, while a condition variable is used to wait for changes to the queue.
- First, the mutex is used to lock the queue whenever a thread attempts to access it. This ensures that only one thread can access the queue at a time. After the thread has finished accessing the queue, it can unlock the mutex.
- Next, a condition variable is used to wait for changes to the queue. When a thread adds an item to the queue, it signals the condition variable to indicate that the queue has changed. This allows threads that are waiting for changes to the queue to be woken up and continue.
- Finally, when a thread attempts to remove an item from the queue, it must first check if the queue is empty. If it is, it can wait on the condition variable until an item is added to the queue. This ensures that the thread will not attempt to remove an item from an empty queue.
Below is the implementation of the above discussion:
// C++ implementation of the above approach #include <condition_variable> #include <iostream> #include <mutex> #include <queue> // Thread-safe queue template < typename T> class TSQueue { private : // Underlying queue std::queue<T> m_queue; // mutex for thread synchronization std::mutex m_mutex; // Condition variable for signaling std::condition_variable m_cond; public : // Pushes an element to the queue void push(T item) { // Acquire lock std::unique_lock<std::mutex> lock(m_mutex); // Add item m_queue.push(item); // Notify one thread that // is waiting m_cond.notify_one(); } // Pops an element off the queue T pop() { // acquire lock std::unique_lock<std::mutex> lock(m_mutex); // wait until queue is not empty m_cond.wait(lock, [ this ]() { return !m_queue.empty(); }); // retrieve item T item = m_queue.front(); m_queue.pop(); // return item return item; } }; // Driver code int main() { TSQueue< int > q; // Push some data q.push(1); q.push(2); q.push(3); // Pop some data std::cout << q.pop() << std::endl; std::cout << q.pop() << std::endl; std::cout << q.pop() << std::endl; return 0; } |
Output
Time Complexity: Best Case : O(1), Worst Case: O(n)
Auxiliary Space: O(n)
"The DSA course helped me a lot in clearing the interview rounds. It was really very helpful in setting a strong foundation for my problem-solving skills. Really a great investment, the passion Sandeep sir has towards DSA/teaching is what made the huge difference." - Gaurav | Placed at Amazon
Before you move on to the world of development, master the fundamentals of DSA on which every advanced algorithm is built upon. Choose your preferred language and start learning today:
DSA In JAVA/C++
DSA In Python
DSA In JavaScript
Trusted by Millions, Taught by One- Join the best DSA Course Today!
Recommend
-
128
7 Techniques for thread-safe classes Almost every Java application uses threads. A web server like Tomcat process each request in a separate worker thread, fat clients process long-running requests in dedicated worker threads, and even ba...
-
86
ump A universal thread-safe memory pool. This simple memory pool can be used if following conditions are satisfied: (1) The memory sizes are some fixed numbers. E.g, 32 ,
-
10
Fix high CPU issue for ASP.NET - Dictionary was not thread-safe We have a ASP.NET application and suffered from high CPU issue occasionally - for years. It’s in production code and hard to reproduce. Fortunately, we got two dum...
-
8
A proper thread safe memory cache The Core 2.2 IMemoryCache is in theory thread safe. But if you call GetOrCreateAsync from multiple threads the factory Func will be called multiple times. Whi...
-
8
3 ways to make your ruby object thread-safe Let’s say you have an object and you know or suspect it might be used (called) from many threads. What can you do to make it safe to use in such a way? 1. Make it...
-
9
How to Implement a Queue in JavaScriptBeing a good developer requires knowledge from multiple disciplines. The first requirement is to know the programming language of your choice. If you’re reading this post, most likely yo...
-
8
How to implement a producer-consumer queue During my most recent class I discussed implementations of simple, multi-threaded, producer-consumer queues: unb...
-
8
<?xml encoding="utf-8" ??>Introduction Redis queue is a library that you can use to create and process a linear collection of jobs on a first-in-first-out basis. You should always use queues in...
-
7
September 15, 2022 #redis How to implement a job queue with Redis ...
-
4
Francis T. O'Donovan Data Science Manager at LeanTaaS – Planet discoverer, researcher, developer, ge...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK