Python Multithreading Tutorial #1 - What is a Thread?

Tech With Tim · Beginner ·🧠 Large Language Models ·7y ago

Key Takeaways

This video tutorial covers the basics of Python multithreading, including what a thread is, how it compares to a process, and how multithreading can improve code efficiency. The tutorial uses Python and its threading module to demonstrate thread creation, switching, and synchronization.

Full Transcript

hey guys and welcome back to a new tutorial series on multi-threading in Python now before I go too far I just want to quickly mention that if you guys need any help throughout these videos uh all this stuff and all the code will be up on my website techwith tim. net and you guys can feel free to join my Discord server where I have a bunch of people that are always willing to help out and talk about programming and coding uh the links in the description for that and also you guys should follow my Twitter for some exclusive updates and when the next videos are coming out um going with that if you guys can like the content uh and you like what I'm doing on this channel consider supporting me for a small donation per month by becoming a patreon or by providing a donation via Paypal um I don't make very much money off of YouTube and any donation really is greatly appreciated okay so with that being said let's get right into this video and talk about what is threading so you probably heard about threading before and it you've probably heard about it talked about in the same kind of sentence as processes and a lot of people get confused on what the difference between a process and a threat is so that's what I'm going to explain here here and we're going to show a bit of an example code near the end of the video illustrating kind of the differences so here I'm in my task manager and you can see we have a long list of processes and you guys have probably done this before open up task manager and maybe ended a task or ended a process and whatnot okay so these are all our processes and essentially what a process is is a program running on your computer so now let's go to the performance Tab and let's go to our CPU and let's have a look down here at the bottom you can see we have 152 processes running and 1,700 threads so what is a thread well essentially each process is made up of different threads could be one thread but often times it's many different threads and a thread is essentially a task associated with a process okay so now we're going to move over to this little illustration where I'm going to kind of try to show this to you so I have kind of uh a bunch of different things on the screen here we're going to link these up in how they work together so we have this python file which is what we write as the programmer okay we have some threads we have some processes we have our computer's memory and a CPU and just take note that this is a four core CPU so let's start with processes we already know what a process is essentially it's a program that's running on our computer now what happens when we create a new process essentially is in uh in memory so in Ram we allocate some space for our process we say well creating this new process so everything that has to do with this process we're going to store in box one and box one is just a little slice of RAM and that slice could be extended or it can be uh it can become smaller but we have like a general location for that process and that's where it stores all of its uh variables all the information that it needs okay and that happens for all of our processes so whenever we create a new process we allocate a little slice of RAM for those processes now when we do that um Ram is kind of like a c and essentially it's going to indicate what needs to run first what needs to run second and what needs to happen on a single core processor what would happen is well we'd read information from Ram like we'd read an instruction and then we'd write something back into RAM and we just keep doing that and keep following kind of the sequence of things that have been added to Ram but on a four core processor instead of doing things one at a time what we can do is we can actually split up all of the different tasks and all of the different processes that we have into well four groups and essentially allowing us to do things four times faster not quite but somewhat okay so we say well if we have four processes let's split these up onto each core of our CPU because each core can perform its own operations and do its own things independent of the other so we'll say well process one which is going to be stored in Ram right can go to core one process two can go to core two 3 to three and four to four you guys get the point right and that's why I labeled them here allowing us essentially to do four things at once in parallel so at the exact same time we can be doing four things now on each core let's say though we can't be doing something at the same time on a core so let's say we need to add a number and then we need to subtract a number and that's like core one's job is to add something then subtract something well we first have to add and then we have to subtract we can't do it we can't do that at the exact same time right we got to perform operation one and then we can do operation two now if we had that split onto two cores well we could technically do those at the same time we could add one and subtract one at the exact same time because they're on two separate cores this is kind of an important concept to understand so now we kind of understand how processes work uh with the CPU they go into RAM they have their own little space and then their kind of instructions and the work that needs to be done gets divvied up between the cores on our CPU essentially allowing us for to do four things at once in parallel at the same time so now let's talk about threads where do these come from well each process is made up of a bunch of different threads and these threads are essentially different tasks that are running now one thread only one thread can be running at a time we can't have two threads running at the exact same time um like they can be um stacked up like we can have two threads that we've created but their their commands and their execution like if we need to add something and subtract things um they have to happen one after another they can't happen in parallel they're happening uh in sequence okay so that's where threads come in they essentially are just a bunch of tasks that make up a process so where does this come in with our python file well up until now likely you've probably just been creating single-threaded programs which mean that we have to wait for one line of code to execute before the next line of code executes um and that's just the way that it works right we can't have two things happening at the same time now when we create threads that is still true except we can actually switch between threads so we can say like maybe we have a function running we have two functions running we have one function that maybe counting to 100 another function that's counting to 50 well let's say maybe the function that's counting to 50 needs to stop for a second uh and wait for maybe some user input or something to happen well rather than not allowing the other function to run what we'll do is we'll simply say okay well if this one's waiting let's switch to the other thread and let that run so I'm going to show you an example now with some code and hopefully this will make this a bit more clear uh but essentially just I hope we kind of understood how this flows a little bit all right so if you get it just a little bit then you guys should be good for this part okay so now I'm just going to run you through some code that I wrote this actually from the python website I just kind of copied and modified it a bit that explains or kind of shows creating two threads and then their execution and how they kind of switch between one another so remember I was saying right that if one thread is waiting for something else to happen like it's not executing any Comm is just sitting there it's idle it's waiting then rather than waiting for that thing to happen let's run something else in the background right we have two threads running and one is waiting well the other thread can start running if that thread starts waiting and the other one has some commands that needs to be executed let's do that because we can never truly do things in Threads at the exact same time we can't do two things like in the exact same like nanc millisecond right they have to happen one after each other but if one thread is not doing something the other thread can be doing something so that's how we kind of switch between things so let me just run this and then we'll really dissect what's happening so let's make this full screen and you can see that we go thread one thread two one two one two and just wait for this to happen sweet so essentially what we've done here is thread one runs okay and it's what what these both these threads are trying to do by the way is count down to zero so starting at five they're trying to go to zero once they get to zero the exit so thread we start thread one and then we start thread two and then thread one runs it goes five thread two runs it goes five okay and then thread one runs thread two runs thread one runs and would you look at this thread one runs again because it's not waiting it just keeps going so now thread one's waiting for a second so thread two goes thread two is waiting for a second thread one goes thread one's done and now thread two goes until it finishes it's kind of a weird execution uh but we'll show why this happens if I just go here so essentially what I'm doing is I'm creating two threads and each thread runs this function it's called print time and all it does is it takes a counter which going to start at five and it tries to get down to zero but notice that I have this time do sleep in here and this time do sleep is essentially delaying the function uh a certain amount of time so my thread one every time it runs delays 1 second and my thread 2 every time it runs delays uh 1.5 seconds so what happens is and we'll bring up this console again is when thread one runs it does this it says while counter uh which means we're not at zero essentially time do sleep delay the delay is 1 second so you can see we wait 1 second and then we run thread one and thread one goes five it prints that out it prints the time and then you can even see here it delays 1 second so it comes back up to this wall Loop delays 1 second and since it's delayed we say okay well this is a perfect opportunity to run thread 2 so thread 2 gets run and you can see that it happens exactly 1 second after thread one runs because well it was waiting right and once that time so so it went okay now thread 2 delays for that little second at time and while thread 2 is delaying well it says okay this is a perfect opportunity to run thread one so then thread one runs and then what happens is thread one delays again right does this little delay and then it says oh well we're delaying thread one nothing's running so let's go to thread two so it swaps goes to thread two runs same thing thread three runs because we're delaying thread two for a second right and then we go back to thread one thread two thread one um and so on now you might notice here that thread one runs twice in a row now that's because well thread one runs all right and see it's only delaying 1 second whereas thread 2 is delaying 1 .5 seconds so this kind of a weird but just think about this example right so thread 2 goes it delays 1 and a half seconds this this delay happens one and a half seconds thread one runs it delays 1 second now the thing is when we go back to thread two it's still delaying like it's still in it's still waiting for 1 and a half seconds to go by so if that's happening and we switch back to thread one thread one well maybe it's done it's delay it's done it's 1 second delay so it just executes again and then it delays for 1 second so we switch back to thread 2 we check that delay that delay is done so we run thread 2 and then we just keep going through the program and notice that it says Exit thread one um just telling us that we're finished we're done counting to five so we're going to get out of that thread and then thread two will just go Um one after each other until it eventually exits and is done and that is kind of how threading works I know this might have been a little bit confusing in the next videos I think things will really clear up when we do some real world examples of threading and maybe a bit of networking stuff which is a good example of threading um yeah with that being said I hope you guys enjoyed the video if you do please make sure you leave a like And subscribe to the channel and let me know if there's anything that you'd like me to improve on in terms of explanation or to explain a little bit better in the next video [Music]

Original Description

This python multithreading tutorial talks about what a thread is and how it compares to a process. Multithreading is a commonly used strategy to improve the efficiency of code. When multiple threads are running if the current thread delays or is waiting for something then the next thread will start executing. Source-Code: Coming soon... Playlist: https://www.youtube.com/watch?v=GFfMuyNUnDs&list=PLzMcBGfZo4-mL_4mo5LbOIdPV8jQ-n4ib ◾◾◾◾◾ 💻 Enroll in The Fundamentals of Programming w/ Python https://tech-with-tim.teachable.com/p... 📸 Instagram: https://www.instagram.com/tech_with_tim 🌎 Website https://techwithtim.net 📱 Twitter: https://twitter.com/TechWithTimm ⭐ Discord: https://discord.gg/pr2k55t 📝 LinkedIn: https://www.linkedin.com/in/tim-rusci... 📂 GitHub: https://github.com/techwithtim 🔊 Podcast: https://anchor.fm/tech-with-tim 💵 One-Time Donations: https://www.paypal.com/donate/?token=... 💰 Patreon: https://www.patreon.com/techwithtim ◾◾◾◾◾◾ ⚡ Please leave a LIKE and SUBSCRIBE for more content! ⚡ Tags: - Tech With Tim - Multithreading in python - Python multithreading tutorial - Python Tutorials
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 0 of 60

← Previous Next →
1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This tutorial teaches the basics of Python multithreading, including thread creation, switching, and synchronization, and demonstrates how multithreading can improve code efficiency. By the end of this tutorial, viewers will be able to create and manage threads in Python and understand the benefits of multithreading.

Key Takeaways
  1. Create a new process
  2. Allocate a slice of RAM for the process
  3. Split tasks into groups to process them faster
  4. Read information from RAM
  5. Write information back into RAM
  6. Create two threads
  7. Switch between threads
  8. Allow other tasks to run while one task is waiting for user input or other resources
  9. Use the time.sleep() function to delay the execution of the threads
💡 Multithreading allows multiple threads to run concurrently, improving code efficiency by reducing wait times and allowing other tasks to run while one task is waiting for resources.

Related AI Lessons

Up next
5 Levels of AI Agents - From Simple LLM Calls to Multi-Agent Systems
Dave Ebbelaar (LLM Eng)
Watch →