Python is a very powerful language that allows the programmer to create highly efficient and reliable applications. There are a lot of programs and libraries that are built using python programming language.
Python is not just a programming language, but it is a high-level language and the main focus is the performance and efficiency of the code.
The Queue is a data structure that is used to store items. The queue has a fixed size and this is the limitation of the queue. Once the size of the queue is reached, it will throw an exception.
What is a queue?
A queue is an array like data structure in which data is inserted at the end and deleted at the front. So, it is basically a FIFO (first-in-first-out) data structure.
- The queue is a data structure used to store and retrieve data from a collection.
- It is a special kind of a stack. It stores the items in a specific order.
- It has a beginning and an end.
- An element is added to a queue by using the add method.
- An element is retrieved from a queue by using the get method.
- Difference between a stack and a queue
- A stack is a data structure used to store and retrieve data from a collection.
- It is a special kind of a queue.
- It stores the items in a FIFO (First In First Out) manner.
- It has a beginning and an end.
- An element is added to a stack by using the push method.
- An element is retrieved from a stack by using the pop method.
Why we need queues?
Queues are used in almost every system in which the order of data is important. They are used in computer programs, software development, games, and web servers.
Example:
Let us see a practical example to understand the difference between a stack and a queue.
Suppose you want to sort the numbers from 1 to 10. You can do it in two ways.
One way is to use a stack: You can use the push method to insert the numbers into the stack. After that you can use the reverse method to get the reversed list of numbers.
The other way is to use a queue: You can use the get method to get the numbers from the queue.
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))
# would show the output intermingled as the separate items of the print statement
# (even the trailing newline) might be printed only after context switch
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() # block until all tasks are done
num_worker_threads = 3
q = Queue()
main()