Multithreading and Asynchronous tasking in Python

Akash Srivastava
Camping with python
5 min readJul 24, 2019

Hey there, I hope you are working on your skills.

“Practice and patience are the keys to being a great programmer”

In this article, I will be explaining to you a programming concept called Multithreading. This article is not about a project, but about a methodology through which we can enhance our program’s performance and use CPU fully. And soon, we will be using multithreading in our projects.

So, What is multithreading?

A program consists of a set of instructions that are loaded on the Ram and then fed to the CPU. CPU processes these instructions one at a time, something like a function in math, you input a value in the function and a result you get some value at the output. You can say that a CPU is like a very advanced boolean function having the capability of performing any task we throw towards it. Multicore CPU has multiple copies of the same boolean function(cores).

Quad-Core CPU

In multicore CPUs, we can run multiple programs in parallel. You already know that a single unit can process one task at a time. If we have 4 cores inside the CPU then, we can run 4 programs at a particular point time. But in reality, the average CPU handles hundreds of tasks running concurrently. What hundreds! yes, even thousands of tasks on some PC.

I was right

Here, multithreading helps in some way.

Multithreading definition: In computer architecture, multithreading is the ability of a central processing unit (CPU) (or a single core in a multi-core processor) to provide multiple threads of execution concurrently, supported by the operating system.[source: Wikipedia]

We can fully utilize the single-core by implementing multithreading and make the single-core act as “multi-core” CPU.

Threads are like micro-tasks inside a program(code), And we can run them independently. The program can have multiple threads. These threads act as a single program.

CPU while execution switches between these threads and creates an illusion that programs are running in parallel.

Illustration

Multiple threads within a process share the same data space with the main thread and can, therefore, share information or communicate with each other more easily than if they were separate processes.

Humor time

Let’s write some code without errors😎

We will use a python library called “threading”.

A thread has three stages :
1. Thread object which targets the function for execution.
2. Start the thread as seperate process.
3. Join the thread to main process.

Let’s code it out:

Note: Search google on this and then try to code.

basics.py

Dissecting the code:

thread1 is the Thread object targetting function printUpto10 with no arguments (args = ()). The same is for thread2. If we want to pass arguments to target function we can do it in the following way:

thread1 = Thread(target = funtion, args =(10,20,))

thread1.start() starts the execution process of the thread1.

thread1.join() is where thread1 is joined in the main program thread after execution.

The output of the program may or may not be the same on multiple executions because these threads are running in parallel so, the output depends upon the start time and speed processor.

Now, Let’s get our hands dirty on asynchronous tasking:

Asynchronous task execution is best when we don’t want to call the desired function manually. For example, we need to process the downloaded photos as soon as it gets downloads, but we have a shitty connection. We just need an asynchronous task running in parallel, listens to the main thread about the images downloaded and executes the image processing part on the go.

Hope this will help

The above illustration elaborates on the inner working of the process.

Let’s code this up

We are building a simple program that finds the square of the number and prints it. We input the numbers in a loop (zero for exiting the program) and the thread on the other side observes the queue.

Try to code on your own first. Have faith in google.

The whole code is divided into two part:
Part 1: Class Process
Part 2: Input

Let’s Build this class Process

Observe the code

In process.py we created a class called Process having stopped(Flag), Q, thread(Thread object). Function start() starts the thread execution. As the execution starts it watches the Queue(Q) waits for any number input getting saved in Q. If any number is found inside the Q then, it will compute the task and pop out the value according to the FIFO rule.

Now, code the Input task:

This looks quite simple

In this, we create an object of the Process class and start the thread, rest is easily understandable.

P.stop() stops the execution by triggering the self.stopped(Flag variable) to true.

Congratulations on completing the code.

I hope this tutorial will help you a lot in your future projects. Share this article with your colleagues and friends.

Complete code: Github

Thanks for being here with me till the end. I am currently in the starting days of writing articles so, please comment below about the article, your comments mean a lot to me.

You can follow me on Twitter, GitHub, Medium, LinkedIn.

Don’t forget to follow Camping with python.

If you have any doubts regarding this tutorial or have any other issue or you want to suggest something, you can comment below.

The next article will be up soon until then keep practicing.

--

--