fbpx

The Most Simple Explanation of Threads and Queues in Python

Everything you need to know about multi-threading

Sachintha Gamage
June 2, 2021 · 10 Mins Read

Parallel processing and threading intimidate beginner programmers. Terms like queue and threads look very strange and complicated. Here, I try to unfold those terms and show how multithreading works. This article is specifically written for Python beginners who are interested in parallelization.

Queue

You arrive at the airport and go to the check-in counter. An airline staff look at your ticket and put you in a queue (or line). Simple, right? Basically, a queue in an airport is a collection of ordered travelers. Those who came earlier will be served first. In the computer programming world, we call it a FIFO (First In First Out) queue. It never happens in an airport, but sometimes in the programming world, we serve the last task or item first. We call it a LIFO (Last In First Out) queue. The other type of queue is the Priority queue. At the airport, those with first-class or business-class tickets are being served first normally. This is exactly how a priority queue works. It gives each person in line a priority.

Although we have 3 kinds of queues, by far FIFO is the most common type in the programming. Let’s create all three kinds of queues in Python.

You can put or insert items in the queue using put() method or call an object from the queue using get() method. The following example shows a simple FIFO queue loading and unloading. First, you make a FIFO queue object and call it q. Then you put numbers from 1 to 5 into the queue using put() method. Finally, in another loop, you get items one by one from the queue and print them.

What is the problem with the mentioned example? The problem is, in this example, we knew the number of items in the queue (which is 5). Therefore, we called them using get() and a fixed loop. In real-world applications, we normally don’t know the number of items in the queue. Therefore, we must loop through all items inside a queue until the queue becomes empty.

How can we check if a queue is empty? using a method called empty() or an attribute called empty. When empty() method or empty attribute returns True, the queue is empty.

You May Also Like

Scroll to Top