The Wayback Machine - https://web.archive.org/web/20241116072623/https://www.geeksforgeeks.org/implement-thread-safe-queue-in-c/
Open In App

Implement thread-safe queue in C++

Last Updated : 14 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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++
// 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
1
2
3

Time Complexity: Best Case : O(1), Worst Case: O(n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Queue? We use min heap in Dijkstra's Algorithm beca
2 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
Check if a queue can be sorted into another queue using a stack
Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: Push and pop elements from the stack Pop (Or Dequeue) from the given Queue. Push (Or Enqueue) in the another Queue. Examples : Inp
9 min read
Reversing a Queue using another Queue
Given a queue. The task is to reverse the queue using another empty queue. Examples: Input: queue[] = {1, 2, 3, 4, 5} Output: 5 4 3 2 1 Input: queue[] = {10, 20, 30, 40} Output: 40 30 20 10 Approach: Given a queue and an empty queue.The last element of the queue should be the first element of the new queue.To get the last element there is a need to
5 min read
Advantages of circular queue over linear queue
Linear Queue: A Linear Queue is generally referred to as Queue. It is a linear data structure that follows the FIFO (First In First Out) order. A real-life example of a queue is any queue of customers waiting to buy a product from a shop where the customer that came first is served first. In Queue all deletions (dequeue) are made at the front and a
3 min read
Difference between Queue and Deque (Queue vs. Deque)
Queue: The queue is an abstract data type or linear data structure from which elements can be inserted at the rear(back) of the queue and elements can be deleted from the front(head) of the queue. The operations allowed in the queue are:insert an element at the reardelete element from the frontget the last elementget the first elementcheck the size
3 min read
Why can't a Priority Queue wrap around like an ordinary Queue?
Priority Queue: A priority queue is a special type of queue in which each element is assigned a priority value. And elements are served based on their priority. This means that elements with higher priority are served first. However, if elements with the same priority occur, they will be served in the order in which they were queued. A priority que
3 min read
Turn a Queue into a Priority Queue
What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the data item stored first will be accessed first". Decla
9 min read
Why does Queue have front but Priority-queue has top in stl?
Why does the queue have front but the priority queue has top in stl? The main difference between a queue and a priority queue is that a queue follows the FIFO (First-In-First-Out) principle, while a priority queue follows a specific priority order. In other words, the elements in a queue are processed in the order they were added, whereas the eleme
8 min read
What is Circular Queue | Circular Queue meaning
A circular queue is an extended version of regular queue in which the last element of the queue is connected to the first element of the queue forming a cycle. Properties of Circular Queue: Along with the properties of a regular queue the circular queue has som other unique properties as mentioned below: Front and rear pointers: Two pointers, one a
4 min read
Difference Between Linear Queue and Circular Queue
Queues are fundamental data structures in computer science that follow the First-In-First-Out (FIFO) principle. Among the various types of queues, linear queues and circular queues are commonly used. While they share some similarities, they differ significantly in structure and operational efficiency. This article explores the concepts, advantages,
4 min read
Difference between Circular Queue and Priority Queue
Queues are fundamental data structures that are used to store and manage a collection of elements. While both circular queues and priority queues are types of queues, they have distinct characteristics and applications. This article will explore the key differences between circular queues and priority queues. Circular Queue:A Circular Queue is an e
4 min read
What is Priority Queue | Introduction to Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved or removed before elements with lower priority values. Each element has a priority value associated with it. When we add an item, it is inserted in a position based on its priority value. There are
15+ min read
Implement dynamic queue using templates class and a circular array
In this article, we will discuss how to create a dynamic circular queue using a circular array having the following functionality: Front(): Get the front item from the queue.Back(): Get the last item from the queue.Push(X): Push the X in the queue at the end of the queue.Pop(): Delete an element from the queue. Below is the step-by-step illustratio
7 min read
How to implement Stack and Queue using ArrayDeque in Java
ArrayDeque in Java The ArrayDeque in Java provides a way to apply resizable-array in addition to the implementation of the Deque interface. It is also known as Array Double Ended Queue or Array Deck. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue. ArrayDeque class implements Queu
6 min read
How to implement size-limited Queue that holds last N elements in Java?
What is Size Limited Queue? Size limited queue is the same as a normal queue but it has the special property that at any time queue can store at max N element, if we try to push more than N elements in the queue then accordingly the elements added at the starting will be removed from the queue means size will remain to fix i.e. N. If you want to kn
3 min read
How to implement Priority Queue - using Heap or Array?
A Priority Queue is a data structure that allows you to insert elements with a priority, and retrieve the element with the highest priority. You can implement a priority queue using either an array or a heap. Both array and heap-based implementations of priority queues have their own advantages and disadvantages. Arrays are generally easier to impl
15+ min read
Most efficient way to implement Stack and Queue together
Introduction to Stack:A stack is a linear data structure in computer science that follows the Last-In-First-Out (LIFO) principle. It is a data structure in which the insertion and removal of elements can only be performed at one end, which is called the top of the stack.In a stack, elements are pushed onto the top of the stack, and elements are pop
15+ min read
Implement a stack using single queue
We are given queue data structure, the task is to implement stack using only given queue data structure.We have discussed a solution that uses two queues. In this article, a new solution is discussed that uses only one queue. This solution assumes that we can find size of queue at any point. The idea is to keep newly inserted element always at fron
6 min read
Implement the insert and delete functions on Priority queue without Array
A priority Queue is a type of queue in which every element is associated with a priority and is served according to its priority. We will use two popular data structures for implementing priority queues without arrays - Fibonacci HeapBinomial HeapFibonacci Heap:Fibonacci heap is a heap data structure that is composed of a collection of min-heap-ord
15+ min read
How to implement stack using priority queue or heap?
How to Implement stack using a priority queue(using min heap)? Asked In: Microsoft, Adobe.  Solution: In the priority queue, we assign priority to the elements that are being pushed. A stack requires elements to be processed in the Last in First Out manner. The idea is to associate a count that determines when it was pushed. This count works as a k
6 min read
Implement Stack and Queue using Deque
Deque also known as double ended queue, as name suggests is a special kind of queue in which insertions and deletions can be done at the last as well as at the beginning. A link-list representation of deque is such that each node points to the next node as well as the previous node. So that insertion and deletions take constant time at both the beg
15 min read
Print all safe primes below N
Given an integer N, the task is to print all safe primes below N safe primes. A safe prime is a prime number of the form (2 * p) + 1 where p is also a prime. The first few safe primes are 5, 7, 11, 23, 47, ... Examples: Input: N = 13 Output: 5 7 11 5 = 2 * 2 + 1 7 = 2 * 3 + 1 11 = 2 * 5 + 1 Input: N = 6 Output: 5 7 Approach: First pre-compute all t
8 min read
POTD Solutions | 18 Oct’ 23 | Eventual Safe States
Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Graph Data Structure but will also help you build up problem-solving skills. We recommend you to try this problem on our Geeksfor
6 min read
Find shortest safe route in a path with landmines
Given a path in the form of a rectangular matrix having few landmines arbitrarily placed (marked as 0), calculate length of the shortest safe route possible from any cell in the first column to any cell in the last column of the matrix. We have to avoid landmines and their four adjacent cells (left, right, above and below) as they are also unsafe.
15+ min read
Eventual Safe States
A directed graph of V vertices and E edges is given in the form of an adjacency list adj. Each node of the graph is labeled with a distinct integer in the range 0 to V – 1. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node, the task is to return an
13 min read
Applications of Queue Data Structure
Introduction : A queue is a linear data structure that follows the "first-in, first-out" (FIFO) principle. It is a collection of elements that supports two primary operations - enqueue and dequeue. In the enqueue operation, an element is added to the back of the queue, while in the dequeue operation, an element is removed from the front of the queu
5 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Data Structures | Queue | Question 1
Following is C like pseudo-code of a function that takes a Queue as an argument, and uses a stack S to do processing. C/C++ Code void fun(Queue *Q) { Stack S; // Say it creates an empty stack S // Run while Q is not empty while (!isEmpty(Q)) { // deQueue an item from Q and push the dequeued item to S push(&S;, deQueue(Q)); } // Run while Stack S is
1 min read
Practice Tags :
three90RightbarBannerImg