Open In App

Multithreaded Priority Queue in Python

Last Updated : 31 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The Queue module is primarily used to manage to process large amounts of data on multiple threads. It supports the creation of a new queue object that can take a distinct number of items.
The get() and put() methods are used to add or remove items from a queue respectively. Below is the list of operations that are used to manage Queue:

  • get(): It is used to add an item to a queue.
  • put(): It is used to remove an item from a queue.
  • qsize(): It is used to find the number of items in a queue.
  • empty(): It returns a boolean value depending upon whether the queue is empty or not.
  • full(): It returns a boolean value depending upon whether the queue is full or not.

A Priority Queue is an extension of the queue with the following properties:

  • An element with high priority is dequeued before an element with low priority.
  • If two elements have the same priority, they are served according to their order in the queue.

Below is a code example explaining the process of creating multi-threaded priority queue:

Example:




import queue
import threading
import time
  
thread_exit_Flag = 0
  
class sample_Thread (threading.Thread):
   def __init__(self, threadID, name, q):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.q = q
   def run(self):
      print ("initializing " + self.name)
      process_data(self.name, self.q)
      print ("Exiting " + self.name)
  
# helper function to process data        
def process_data(threadName, q):
   while not thread_exit_Flag:
      queueLock.acquire()
      if not workQueue.empty():
         data = q.get()
         queueLock.release()
         print ("% s processing % s" % (threadName, data))
      else:
         queueLock.release()
         time.sleep(1)
  
thread_list = ["Thread-1", "Thread-2", "Thread-3"]
name_list = ["A", "B", "C", "D", "E"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
  
# Create new threads
for thread_name in thread_list:
   thread = sample_Thread(threadID, thread_name, workQueue)
   thread.start()
   threads.append(thread)
   threadID += 1
  
# Fill the queue
queueLock.acquire()
for items in name_list:
   workQueue.put(items)
  
queueLock.release()
  
# Wait for the queue to empty
while not workQueue.empty():
   pass
  
# Notify threads it's time to exit
thread_exit_Flag = 1
  
# Wait for all threads to complete
for t in threads:
   t.join()
print ("Exit Main Thread")



Output:

initializing Thread-1
initializing Thread-2initializing Thread-3

Thread-2 processing AThread-3 processing B

Thread-3 processing C
Thread-3 processing D
Thread-2 processing E
Exiting Thread-2
Exiting Thread-1
Exiting Thread-3
Exit Main Thread

Note: The output may differ depending upon the device specifications and processing power.



Previous Article
Next Article

Similar Reads

Priority Queue using Queue and Heapdict module in Python
Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. queue.PriorityQueue(maxsize) It is a constructor for a priority queue. maxsize is the number of eleme
3 min read
Multithreaded download of yahoo stock history with Python - yfinance
Yfinance is a python package that enables us to fetch historical market data from Yahoo Finance API in a Pythonic way. It becomes so easy for all the Python developers to get data with the help of yfinance. We can easily download historical stock data from yfinance, but the problem is, it is very time taking. Hence, we use multithreading for coveri
3 min read
Multithreaded crawler in Python
In this article, we will describe how it is possible to build a simple multithreading-based crawler using Python. Modules Needed bs4: Beautiful Soup (bs4) is a Python library for extracting data from HTML and XML files. To install this library, type the following command in IDE/terminal. pip install bs4 requests: This library allows you to send HTT
6 min read
Simple Multithreaded Download Manager in Python
Introduction A Download Manager is basically a computer program dedicated to the task of downloading stand alone files from internet. Here, we are going to create a simple Download Manager with the help of threads in Python. Using multi-threading a file can be downloaded in the form of chunks simultaneously from different threads. To implement this
4 min read
Priority Queue in Python
Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element wit
2 min read
Heap and Priority Queue using heapq module in Python
Heaps are widely used tree-like data structures in which the parent nodes satisfy any one of the criteria given below. The value of the parent node in each level is less than or equal to its children's values - min-heap.The value of the parent node in each level higher than or equal to its children's values - max-heap. The heaps are complete binary
5 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
Difference between queue.queue vs collections.deque in Python
Both queue.queue and collections.deque commands give an idea about queues in general to the reader but, both have a very different application hence shouldn't be confused as one. Although they are different and used for very different purposes they are in a way linked to each other in terms of complete functionality. Before we jump into what they a
3 min read
Python multiprocessing.Queue vs multiprocessing.manager().Queue()
In Python, the multiprocessing module allows for the creation of separate processes that can run concurrently on different cores of a computer. One of the ways to communicate between these processes is by using queues. The multiprocessing module provides two types of queues: The Queue class is a simple way to create a queue that can be used by mult
10 min read
Python | Priority key assignment in dictionary
Sometimes, while working with dictionaries, we have an application in which we need to assign a variable with a single value that would be from any of given keys, whichever occurs first in priority. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This task can be performed in a brute force manner using loop. I
4 min read
three90RightbarBannerImg