Have you ever worked with threads? The thread is nothing but a process or task. The main benefit of using thread is you can execute multiple tasks at the same time. In this Python Threading Example, we will see how do we create Threads and work with parallel execution in python.
What is Thread?
I guess you already know about a thread. But still, if you don’t know; A thread is a sequence of instructions that operating system executes independently.
The above statement was the definition, but here we don’t worry about the definition and other theoretical things at all.
So let’s, assume we came into a situation where we want to execute some methods parallelly, or you can say we want to perform multiple tasks at the same time. Then, we can play the functions in their separate threads.
Using thread improves execution time, and is very useful when we need to perform multiple tasks at the same time.
An Example Code
Let’s first see a simple python program where I will be executing two methods sequentially.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import time #First Method def greet_them(people): for person in people: print("Hello Dear " + person + ". How are you?") time.sleep(0.5) #Second Method def assign_id(people): i = 1 for person in people: print("Hey! {}, your id is {}.".format(person, i)) i += 1 time.sleep(0.5) people = ['Richard', 'Dinesh', 'Elrich', 'Gilfoyle', 'Gevin'] t = time.time() greet_them(people) assign_id(people) print("Woaahh!! My work is finished..") print("I took " + str(time.time() - t)) |
What We Did?
In the above code, we have two methods greet_them() and assign_id(). Both functions are taking a single parameter. We are passing an array containing some names.
The method greet_them() is displaying a greeting message for each person in the array.
The method assign_id() is assigning an id to each person in the array.
Now inside both methods, we are sleeping the loop iteration for 0.5 seconds. It will stop the loop for 0.5 seconds, and our process will be in the idle state.
Then at the end, we are also printing the total time taken to process everything sequentially.
Output of the Code
On executing the above code, you will get this output.
You can see the process executed sequentially and we have the total processing time as well which is 5 seconds.
You can see the process executed sequentially and we have the total processing time as well which is 5 seconds.
Now let’s do the same thing with thread, and we will execute both methods concurrently with the help of threads.
Python Threading Example
First, let’s understand some basics about the thread. So whenever you want to create a thread in python, you have to do the following thing.
Step #1: Import threading module. You have to module the standard python module threading if you are going to use thread in your python code.
Step #2: We create a thread as threading.Thread(target=YourFunction, args=ArgumentsToTheFunction).
Step #3: After creating the thread, we start it using the start() function.
Step #4: We also call the join() function to stop the thread after completion of the task.
So, now let’s modify our code, and call the methods in their separate threads. Feeling Excited? 😛
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import time import threading # Python Threading Example for Beginners # First Method def greet_them(people): for person in people: print("Hello Dear " + person + ". How are you?") time.sleep(0.5) # Second Method def assign_id(people): i = 1 for person in people: print("Hey! {}, your id is {}.".format(person, i)) i += 1 time.sleep(0.5) people = ['Richard', 'Dinesh', 'Elrich', 'Gilfoyle', 'Gevin'] t = time.time() #Created the Threads t1 = threading.Thread(target=greet_them, args=(people,)) t2 = threading.Thread(target=assign_id, args=(people,)) #Started the threads t1.start() t2.start() #Joined the threads t1.join() t2.join() print("Woaahh!! My work is finished..") print("I took " + str(time.time() - t)) |
The code above is straightforward, and I guess no explanation is needed. Just remember we don’t call the method in the target=, we just write the name so no parenthesis here. Then the arguments are passed with the second parameter.
The above code will give this output.
You see this time it didn’t execute sequentially. And the overall execution time is reduced by 50%. So that is why we use Threads.
So that’s all for this Python Threading Example friends. I hope you understood some basics with this Python Threading Example. Still, if you have any question, then please leave your comments.
If you found this Python Threading Example helpful, then please SHARE it with your friends. Thank You 🙂
Nice post, u really made it simple
awesome post. good for beginners.