Python Program: A Queue of Tasks

CWC
2 Min Read

Python Program: A Queue of Tasks

A queue is a linear type of data structure used to store the data sequentially. The concept of a queue is based on the first in first out, which means “First in First Out“. You are also known as “first come first severed“. The queue has the two ends front (enqueue) and rear (dequeue). The next element is inserted from the rear end and removed from the front end.

A queue is a First-In-First-Out (FIFO) data structure.

  • An item is added at the tail (enqueue)
  • An item is removed at the head (dequeue)

Below is the sample program for A Queue of Tasks in python:

from queue import Queue
from threading import Thread

def source():
"""Returning the list of tasks"""
return range(1, 10)

def do_work(item):
print("Working on item " + str(item) + "\n", end="")
# print("Working on item ", str(item))
# This would show the output intermingled as the separate items of the print statement
# (even the trailing newline) this might be printed only after context switch statement

def worker():
while True:
item = q.get()
do_work(item)

q.task_done()

def main():
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()

for item in source():
q.put(item)

q.join()
# This to block until all tasks are completed
num_worker_threads = 3
q = Queue()
main()
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version