Python Tutorial - 26. Multithreading - Introduction
Key Takeaways
This video tutorial covers the basics of multithreading in Python, including what is multithreading, how to import the threading module, and how to implement multithreading in a Python program using the threading module and creating multiple threads.
Full Transcript
Hello friends, in today's code basics coding tutorial, we are going to talk about multi-threading in Python. Before we begin with Python multi-threading, let's first understand in general what multi-threading means when it comes to computer science. Multi-threading I often explain uh by giving the example of a busy mom. Uh as you see in this picture, busy mom usually juggles between multiple tasks. So she might be cooking food and at the same time she has to take care of baby and she often gets a phone call and she needs to handle that as well in parallel. So as you see on the right hand side, mom starts by cooking food and at some point you see in this in the green line she has to switch to another task of taking care of uh a baby and then at some point here uh she gets a phone call so she needs to handle that as well. So in this time period, so this vertical slice indicates the time progression. In this time period, she's cooking food, taking care of baby and uh handling phone call. So each of these lines are individual tasks that mom is handling. And when it comes to programming, they are called threads. So mom is handling three threads. Cooking food, taking care of baby and handling phone call. Hence mom is doing multi-threading. Similarly, Python program can handle multiple tasks at the same time and that program uh is called to be doing multi-threading. Okay. So we going to work on a problem where I have an array a list of numbers and I want to calculate the square of each of these numbers and I want to print those numbers at the same time. I want to calculate cube of each of these numbers and print them. So I have to handle two task basically calculating squares and calculating numbers calculating cubes of these numbers in the array. uh so it's simple to write two functions so what I have written here is I have written the first function which is calculating square which takes numbers array as an input I go through the array and I print the square here now I'm introducing a time sleep so this time module what it does is it waits for 2 seconds before printing this number and I will tell you in a bit why I'm doing this But for now just assume that this goes through an input array and it just prints square of each of these numbers. This function is exactly similar to this function except that instead of square it is calculating the cube of those numbers. Okay. And I'm calculating I'm calling calculating square and calculate cube one by one. And then I'm printing done when I'm done. And I'm also doing something else which is uh calculating how much time it took to execute these two functions. Okay. So it's fairly simple program. Uh so let let me just run it. Okay. So as you can see here I have this array 2 389. It first printed 4 9 64 81 uh the square of these numbers and the cube of these numbers. So cube of 2 is 2 into 2 into 2 is 8. 3 cube is 27 because 3 into 3 9 into 3 uh is equal to 27 and so on. Overall this program took 1.6 second. Let me execute one more one more time. Again it took 1.6 seconds. So note down this number. this program is taking 1.6 second to execute. Okay. Now the reason I introduced this time uh delay here is that just to demonstrate in which scenario multi-threading could be useful. Here you are first calculating square and then calculating cube. Now when you're waiting here what's happening is your CPU is idle. See your CPU is doing nothing. Okay. Now you might have this scenario when let's say in real life you might be calling a web service or you might be waiting for a packet on your network socket. So at that time you are waiting and your CPU in your PC is not doing anything. Multi-threading tries to utilize this idle time and during that idle time you want to give CPU some work. Okay. So let's use multi-threading and improve this number. So it's taking right now 1.6 second. Using multi-threading we will improve the time will execute this program much faster. Okay. So first thing you need to do in order to use multi-threading is import threading module. Okay. This is a standard Python module used for multi-threading. And now instead of calling these fun functions directly, so I'm going to remove these. And what I'm going to do is I'm going to create a thread. So I'll say threading uh threading dot thread. Okay. and target equal to. So your target is your worker function the the task simple task that you want to execute. This is similar to mom taking a phone call for example or or handling baby. So in our case that task is calculating square. Okay. So you mention your function name after target and in your args you will mention your arguments. So here your arguments is your array. So this is a tpple that you're passing as an input. So if you have multiple arguments to this function, you will pass multiple arguments here. Okay. So this way you created the first thread and now I'm going to create the second thread and here my function will be calculating cube. Okay. So by doing this I'm creating these two threads T1 and T2. Now I just created a threads two threads and I need to uh start them now. So I will say T1 dot start then T2 dot start. So this will execute these two programs in parallel. Okay. And then you need to say T1.join join T2 dot join what join will do is it will wait until these this thread is done basically T1 dot join means now wait here until t1 is done t1 meaning until this uh this calculate square function is finished and then you you want to print done okay so let's execute this program Now nice. So as you see here now what it is doing is it is not executing these two functions in a sequence. So first is it calculated a square. Okay. So it calculated a square here. Then it went into this loop one more time and it and then it started waiting. So while it was waiting here the other function was also executing in parallel. So meanwhile it printed cube. So you see cube here. So that's why you see square and cube because there are two tasks being performed simultaneously in parallel. Okay. So whichever task gets done you get the output of that here. And you see that now our program is taking half the time compared to what it used to take before. So here is8. If you recall previously it used to take 1.6 second. Now it is taking only.8 second. Okay. Now let's compare this with our busy mom example. So here the main program started. So this red line is called the main thread. Then at some point we started calculating square of numbers. So which is this green line. So we just spawned a new thread which is this green color line. So that we did by doing this T1 start. So when you say T1 start what you're doing is you are just basically start starting execution of this new thread. Then at some point you started calculating Q of numbers which is this D2 dot start and then when the they are done they come back to this main program. So these points here are basically T1.join and T2.join. Join means you are done with your usual thread. Now the execution joins back into your main program your main thread. Okay. So again comparing it with bimom is kind of very similar thing that your program doing. Okay. So multi-threading is typically used when as explained previously when your CPU is idle it is waiting for something. I didn't have a sophisticated example that's why I introduce artificial delay. But in in your real life you'll be calling let's say web service. web service might take few seconds to give you back the response during that time. If you want to optimize the performance of your program and you make your CPU do some work then you can definitely use uh multi-threading. Now multi-threading in Python is a little special because there is something called a glo global interpreter lock that uh prevents you from using the true benefits of multi-threading. But in any case whenever you are waiting and when you are doing IO bound operation you can still use multi-threading. So go ahead and use it. And if you want to do real CPU in intensive work and you're not waiting for an IIO type operation then you need to use multiprocessing. So all those are little advanced concepts which we will cover in future videos. Okay. So that was a sweet little introduction on multi-threading. Thank you very much for watching.
Original Description
This tutorial covers what is multi-threading and then shows how to create multiple threads in python program. It explains what is multithreading with examples, how to import the threading module and how to implement multi-threading.
Exercise: https://github.com/codebasics/py/blob/master/Basics/Exercise/26_multithreading/26_multithreading.md
Topics that are covered in this Python Video:
0:00 What is multithreading?
1:49 Example of multithreading
5:20 Import threading module and implementing multi-threading
Code used in this tutorial: https://github.com/codebasics/py/blob/master/Multiprocessing/multthreading_introduction.py
Do you want to learn technology from me? Check https://codebasics.io/ for my affordable video courses.
Next Video:
Python Tutorial - 27. Multiprocessing Introduction: https://www.youtube.com/watch?v=Lu5LrKh1Zno&list=PLeo1K3hjS3uv5U-Lmlnucd7gqF-3ehIh0&index=30
Website: https://codebasics.io/
#️⃣ Social Media #️⃣
📸 Codebasics Instagram: https://www.instagram.com/codebasicshub/
🔊 Codebasics Facebook: https://www.facebook.com/codebasicshub
📝 Codebasics LinkedIn: https://www.linkedin.com/company/codebasics/
📱 Codebasics X handle: https://twitter.com/codebasicshub
📸 Dhaval's Instagram: https://www.instagram.com/dhavalsays/
📝 Dhaval's LinkedIn: https://www.linkedin.com/in/dhavalsays/
📱 Dhaval's X handle: https://x.com/dpcodebasics
Playlist
Uploads from codebasics · codebasics · 42 of 60
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
41
▶
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Python Tutorial - 1. Install python on windows
codebasics
Python Tutorial - 2. Variables
codebasics
Python Tutorial - 3. Numbers
codebasics
Python Tutorial - 4. Strings
codebasics
Python Tutorial - 5. Lists
codebasics
Python Tutorial - 6. Install PyCharm on Windows
codebasics
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
Python Tutorial - 8. If Statement
codebasics
Python Tutorial - 9. For loop
codebasics
Python Tutorial - 10. Functions
codebasics
Python Tutorial - 11. Dictionaries and Tuples
codebasics
Python Tutorial - 12. Modules
codebasics
Python Tutorial - 13. Reading/Writing Files
codebasics
How to install Julia on Windows
codebasics
Python Tutorial - 14. Working With JSON
codebasics
Julia Tutorial - 1. Variables
codebasics
Julia Tutorial - 2. Numbers
codebasics
Python Tutorial - 15. if __name__ == "__main__"
codebasics
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
Python Tutorial - 16. Exception Handling
codebasics
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
Julia Tutorial - 4. Strings
codebasics
Python Tutorial - 17. Class and Objects
codebasics
Julia Tutorial - 5. Functions
codebasics
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
Julia Tutorial - 7. For While Loop
codebasics
Python Tutorial - 18. Inheritance
codebasics
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
Julia Tutorial - 10. Exception Handling
codebasics
Python Tutorial - 19. Multiple Inheritance
codebasics
Python Tutorial - 20. Raise Exception And Finally
codebasics
Python Tutorial - 21. Iterators
codebasics
Python Tutorial - 22. Generators
codebasics
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
Python Tutorial - 24. Sets and Frozen Sets
codebasics
Python Tutorial - 25. Command line argument processing using argparse
codebasics
Debugging Tips - What is bug and debugging?
codebasics
Debugging Tips - Conditional Breakpoint
codebasics
Debugging Tips - Watches and Call Stack
codebasics
Python Tutorial - 26. Multithreading - Introduction
codebasics
Git Tutorial 3: How To Install Git
codebasics
Git Tutorial 1: What is git / What is version control system?
codebasics
Git Tutorial 2 : What is Github? | github tutorial
codebasics
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
Git Github Tutorial 10: What is Pull Request?
codebasics
Git Tutorial 7: What is HEAD?
codebasics
Git Tutorial 9: Diff and Merge using meld
codebasics
Difference between Multiprocessing and Multithreading
codebasics
Python Tutorial - 27. Multiprocessing Introduction
codebasics
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
Git Tutorial 8 - .gitignore file
codebasics
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
Python Tutorial - 30. Multiprocessing Lock
codebasics
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
What is code?
codebasics
Python unit testing - pytest introduction
codebasics
Related Reads
📰
📰
📰
📰
What Workflow Builders Learn When AI Draft Quality Improves but Publishing QA Still Breaks: Practical Notes for Builders
Dev.to AI
Meshy AI 3D Generator Review 2026: 185 MB Per House, $193 to Ship It
Medium · AI
5 Claude Tricks That Feel Almost Like Cheating
Medium · Data Science
[Video] I Tested Grok 4.7 With One Simple Job: Turn My vi Task Files Into a Bash Agenda
Dev.to AI
Chapters (3)
What is multithreading?
1:49
Example of multithreading
5:20
Import threading module and implementing multi-threading
🎓
Tutor Explanation
DeepCamp AI