Queue: Thread_safe FIFO Implementation

Cherima Momin
AI Perceptron
Published in
4 min readDec 26, 2020

A queue is a simple data structure that allow us to store and retrieve data sequentially. There are two types of Queue, FIFO, and LIFO.

Here the queue module provides a first-in, first-out (FIFO) data structure suitable for multi-threaded programming, also used to pass data between producer and consumer threads safely.

The size of a Queue (the number of elements it contains) may be restricted to throttle memory usage or processing.

1.)Basic FIFO Queue:

Here in FIFO queue, the element that goes first will be the first to come out.

FIFO(first in first out)-

  • put()-Used to add elements to one “end” of the sequence
  • get()- Used to remove elements from the other end

The examples for FIFO queue given below-

Output-

Flow chart-

2.)LIFO Queue

The element that is entered last will be the first to come out.To work with LIFO, i.e., last in the first out queue, we need to import the queue module and make use of the LifoQueue() method.

LIFO(Last in first out)

The examples for LIFO queue-

Output-

Flow_Chart

3.)Priority Queue

Priority Queue is a more specialized data structure than Queue. Instead of dequeuing the oldest element, a priority queue sorts and dequeues elements based on their priorities. Lower the value, the higher the priority. Following are the principal methods of a Priority Queue

  • insert / enqueue
  • remove / dequeue

A simple implementation of priority Queue

output

Insert / Enqueue Operation

Here whenever an element is inserted into queue, priority queue inserts the item according to its order.

  • check if the queue is full
  • for the first element, set value of FRONT to 0
  • increase the REAR index by 1
  • add the new element in the position pointed to by REAR

Remove / Dequeue Operation

Here whenever an element is to be removed from queue, queue gets the element using item count. Once the element is removed. Item count is reduced by one.

  • check if the queue is empty
  • return the value pointed by FRONT
  • increase the FRONT index by 1
  • for the last element, reset the values of FRONT and REAR to -1

Key differences between Priority Queue and Queue:
1)In Queue, the oldest element is dequeued first .when elements are popped from a simple queue, a FIFO order of data is obtained in the result

2)While, in Priority Queue, element based on highest priority is dequeued.
When elements are popped out of a priority queue then result obtained in either sorted in Increasing order or in Decreasing Order.

--

--