Python Tutorial - 26. Multithreading - Introduction

codebasics · Beginner ·🛠️ AI Tools & Apps ·10y ago

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
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from codebasics · codebasics · 42 of 60

1 Python Tutorial - 1. Install python on windows
Python Tutorial - 1. Install python on windows
codebasics
2 Python Tutorial - 2. Variables
Python Tutorial - 2. Variables
codebasics
3 Python Tutorial - 3. Numbers
Python Tutorial - 3. Numbers
codebasics
4 Python Tutorial - 4. Strings
Python Tutorial - 4. Strings
codebasics
5 Python Tutorial - 5. Lists
Python Tutorial - 5. Lists
codebasics
6 Python Tutorial - 6. Install PyCharm on Windows
Python Tutorial - 6. Install PyCharm on Windows
codebasics
7 PyCharm Tutorial - 7. Debug python code using PyCharm
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
8 Python Tutorial -  8. If Statement
Python Tutorial - 8. If Statement
codebasics
9 Python Tutorial - 9. For loop
Python Tutorial - 9. For loop
codebasics
10 Python Tutorial -  10. Functions
Python Tutorial - 10. Functions
codebasics
11 Python Tutorial - 11. Dictionaries and Tuples
Python Tutorial - 11. Dictionaries and Tuples
codebasics
12 Python Tutorial - 12. Modules
Python Tutorial - 12. Modules
codebasics
13 Python Tutorial - 13. Reading/Writing Files
Python Tutorial - 13. Reading/Writing Files
codebasics
14 How to install Julia on Windows
How to install Julia on Windows
codebasics
15 Python Tutorial - 14. Working With JSON
Python Tutorial - 14. Working With JSON
codebasics
16 Julia Tutorial - 1. Variables
Julia Tutorial - 1. Variables
codebasics
17 Julia Tutorial - 2. Numbers
Julia Tutorial - 2. Numbers
codebasics
18 Python Tutorial - 15. if __name__ == "__main__"
Python Tutorial - 15. if __name__ == "__main__"
codebasics
19 Julia Tutorial - Why Should I Learn Julia Programming Language
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
20 Python Tutorial  - 16. Exception Handling
Python Tutorial - 16. Exception Handling
codebasics
21 Julia Tutorial - 3. Complex and Rational Numbers
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
22 Julia Tutorial - 4. Strings
Julia Tutorial - 4. Strings
codebasics
23 Python Tutorial -  17. Class and Objects
Python Tutorial - 17. Class and Objects
codebasics
24 Julia Tutorial - 5. Functions
Julia Tutorial - 5. Functions
codebasics
25 Julia Tutorial - 6. If Statement and Ternary Operator
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
26 Julia Tutorial - 7. For While Loop
Julia Tutorial - 7. For While Loop
codebasics
27 Python Tutorial  - 18. Inheritance
Python Tutorial - 18. Inheritance
codebasics
28 Julia Tutorial - 8. begin and (;) Compound Expressions
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
29 Python Tutorial - 12.1 - Install Python Module (using pip)
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
30 Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
31 Julia Tutorial - 10. Exception Handling
Julia Tutorial - 10. Exception Handling
codebasics
32 Python Tutorial  - 19. Multiple Inheritance
Python Tutorial - 19. Multiple Inheritance
codebasics
33 Python Tutorial - 20. Raise Exception And Finally
Python Tutorial - 20. Raise Exception And Finally
codebasics
34 Python Tutorial - 21. Iterators
Python Tutorial - 21. Iterators
codebasics
35 Python Tutorial - 22. Generators
Python Tutorial - 22. Generators
codebasics
36 Python Tutorial - 23. List Set Dict Comprehensions
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
37 Python Tutorial - 24. Sets and Frozen Sets
Python Tutorial - 24. Sets and Frozen Sets
codebasics
38 Python Tutorial - 25. Command line argument processing using argparse
Python Tutorial - 25. Command line argument processing using argparse
codebasics
39 Debugging Tips - What is bug and debugging?
Debugging Tips - What is bug and debugging?
codebasics
40 Debugging Tips - Conditional Breakpoint
Debugging Tips - Conditional Breakpoint
codebasics
41 Debugging Tips - Watches and Call Stack
Debugging Tips - Watches and Call Stack
codebasics
Python Tutorial - 26. Multithreading - Introduction
Python Tutorial - 26. Multithreading - Introduction
codebasics
43 Git Tutorial 3:  How To Install Git
Git Tutorial 3: How To Install Git
codebasics
44 Git Tutorial 1: What is git / What is version control system?
Git Tutorial 1: What is git / What is version control system?
codebasics
45 Git Tutorial 2 : What is Github? | github tutorial
Git Tutorial 2 : What is Github? | github tutorial
codebasics
46 Git Tutorial 4: Basic Commands: add, commit, push
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
47 Git Tutorial 5: Undoing/Reverting/Resetting code changes
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
48 Git Tutorial 6: Branches (Create, Merge, Delete a branch)
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
49 Git Github Tutorial 10: What is Pull Request?
Git Github Tutorial 10: What is Pull Request?
codebasics
50 Git Tutorial 7: What is HEAD?
Git Tutorial 7: What is HEAD?
codebasics
51 Git Tutorial 9: Diff and Merge using meld
Git Tutorial 9: Diff and Merge using meld
codebasics
52 Difference between Multiprocessing and Multithreading
Difference between Multiprocessing and Multithreading
codebasics
53 Python Tutorial - 27. Multiprocessing Introduction
Python Tutorial - 27. Multiprocessing Introduction
codebasics
54 Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
55 Git Tutorial 8 - .gitignore file
Git Tutorial 8 - .gitignore file
codebasics
56 Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
57 Python Tutorial - 30. Multiprocessing Lock
Python Tutorial - 30. Multiprocessing Lock
codebasics
58 Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
59 What is code?
What is code?
codebasics
60 Python unit testing - pytest introduction
Python unit testing - pytest introduction
codebasics

This tutorial teaches the basics of multithreading in Python, including how to create multiple threads and implement multithreading in a Python program. It covers the importance of concurrency and parallel processing in programming.

Key Takeaways
  1. Import the threading module
  2. Create a new thread using the Thread class
  3. Start the thread using the start method
  4. Use the join method to wait for the thread to finish
  5. Implement multithreading in a Python program
💡 Multithreading allows for concurrent execution of multiple threads in a program, improving responsiveness and system utilization.

Related Reads

📰
What Workflow Builders Learn When AI Draft Quality Improves but Publishing QA Still Breaks: Practical Notes for Builders
Learn how improved AI draft quality affects workflow builders and publishing QA, and what practical steps to take to ensure seamless content delivery
Dev.to AI
📰
Meshy AI 3D Generator Review 2026: 185 MB Per House, $193 to Ship It
Learn how Meshy AI 3D Generator works and its implications on data storage and shipping costs
Medium · AI
📰
5 Claude Tricks That Feel Almost Like Cheating
Boost productivity with Claude by using 5 tricks that simplify workflows and enhance efficiency
Medium · Data Science
📰
[Video] I Tested Grok 4.7 With One Simple Job: Turn My vi Task Files Into a Bash Agenda
Learn how to use Grok 4.7 to automate task management by converting 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
Up next
How to Get Your Brand Cited by ChatGPT, Claude and Gemini
Arvow
Watch →