Python Tutorial 20: Understanding Python Threads and Threading

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys this is paul mcquarter from toptechboy.com and we're here today with episode number 20 in our incredible new tutorial series where you're going to learn python or you're going to die trying i'm gonna need you to pour yourself a nice strong cup of coffee that is straight black coffee hot no sugar no sweeteners none needed why because you guys watching this channel your jet fighter aircraft and what does a jet fighter aircraft need needs its jet fuel go get you some i am also going to need you to go ahead and fire up your most excellent visual studio code and as you're firing up visual studio code as always i want to give a shout out to you guys who are helping me out over at patreon it is your encouragement and your support that keeps this great content coming you guys that are not helping out yet look down in the description there is a link over to my patreon account think about hopping on over there and hooking a brother up but enough of this shameless self-promotion let's jump in and let's talk about what we are going to learn today we are going to learn about how to do threading threads and threading in python and actually this is a pretty important thing for the direction that we're going to be going with these future lessons and kind of review a little bit what did we learn about last week we learned about how to do classes and methods okay how to use classes and methods and hopefully that lesson made sense to you and then today we're going to learn another very very important concept that it's a little bit kind of associated with classes and methods it's kind of an advanced uh python technique and it is called threading okay what is the problem that we have with computer programming computer program executes one line of code at a time and it doesn't move to the next line until it finishes this line and so it goes down the page line by line by line and it does one thing at once okay why is this a problem well imagine that we start working with some sensors and start working with maybe we're talking to arduino as we're trying to draw a graph as we're trying to do this different stuff and all of a sudden it doesn't work to do one things at a time you've got to do more than one thing at a time all right and i'm going to show you how to do that today but i think the instructional material out there on threading is really really complicated and they just start banging it out like you already know what they're doing and so i'm going to give you a very simple problem and that very simple problem is going to illustrate the need for threading okay and so now i am going to switch over to my visual studio code i'm going to get me a little go juice here all right so i will get out of your way and let's just start with some relatively simple concepts so i'm going to come up here and we are going to go to our python files folder i'm going to create a new file and then i am going to call this the red example.py.py is pretty important and boom we've got ourselves a fresh new python program that is just waiting to be written it is just waiting to be written so let's imagine that we have a box okay and that box is gonna what we wanna do is we wanna open the box and then we wanna like let's say leave it open for five seconds and then we wanna close the box and we wanna leave it closed for five seconds and then open the box and then close the box also the box it has a little led inside of it and that led can be on or it can be off so the box is opening and closing we're going to want to do that and then we're going to be turning the led on and the led off all right so let's just kind of play around with this and let's uh let's say that we're just going to do the open and close business first and so what i could say is i could do something really simple like i'm going to need to be doing timing right i'm going to be needing to put some delays in here so i need to import a library that allows me to put delays in so i'm going to say import the time library i'm going to do this a little bit different from time import star from time import star what that just means is go to the time library and import everything out of the time library so sometimes there's little sub libraries in the library and you can just grab one we're going to grab everything all right and so now what we are going to do is we are going to say print and we are going to print my box is open okay and now what do we want to do we want to wait so i'm going to say sleep for five seconds all right then what i want to do i want to close the box so i'm going to print my box is closed like that [Music] all right now this should be a fairly simple thing to run and so let's just hop over here and let's run this thing okay it's pretty obvious so you open the box my box is open it waits five seconds and then it says my box is closed all right and i'm realizing that if we want to keep doing this this needs to be like let's say inside of a while loop so i am going to say while and then while true when is true true true is always true so i've created a what i've created an old infinite loop and then i need to tab this stuff over so it'll be inside of there so now this should just open the box close the box now of course in a real program you would like give it a command like maybe you would send a command to a servo that would open the box and then you would wait five seconds and then you would send a command to close the box all right so you would open the box and close the box and my goodness we need to sleep again five after that so where i'm just saying print just imagine that it's a command to move the servo to open it well then you want to wait five seconds and then you want to move the servo to close it right so this is this is is very simple but it is showing you what is going to be the problem so look down here boom my box is open we're going to get a little go juice here my box is closed very poor formatting there let me fix that kill this you get the idea of what we're doing uh though don't you okay my box is open wait five seconds my box is closed looking good my box is open and then my box is closed okay so we're sitting there and we're opening the box and closing the box and opening the box and closing the box but remember we also have an led and we want to be blinking that led okay and so we want to blink that led and let's say we want to have it on for a second and off for a second well if i just came down here and said print if i just came down here and said print oh man this is annoying me i'm going to turn that auto complete off one of these days and it's going to make you guys happy because it's not going to be covering things up so then i could say like print my led is on and then i could i could come down here and then i could sleep for one and then i could say print my led is off [Music] and then i could sleep for one all right now what is the problem with this well i'm going to open the box and wait five and close the box and wait five and then turn the led on so the box is going to be open and then it's going to be closed and then finally i'm going to turn the led on and off and then that gets this you see what i want i want to turn the led on right here okay but i can't turn it on here because then it would stay on for five seconds you see once you hit one of these sleeps or one of these delays that sits at that line of code and so while i'm sitting here while i am sitting here waiting to leave that box open for five seconds my code is locked up here on the sleep five and i can't be turning the led on and off over here because the whole program the whole enchilada has locked up on this one thing and so this shows you the problem with programming you operate or you execute one line of code at a time and it stays at that line of code until it's ready to go to the next line does that kind of show you what my problem is okay well this is where threading comes in and what we're going to do is you launch a thread and that thread is operating independent of this thread so i have one thread that is opening and closing the box and then this other thread acts like a whole different program that's turning the light on and off okay so we're going to create multiple threads and they don't interfere with each other well to do something like that what we're probably going to need to do is just start by writing some functions because you can imagine that you have a function that does one thing you have a function that does another thing now we got to run both functions at the same time so let's kind of rewrite this with functions we're still going to need our old friend mr time old man tom we're going to need him and we're also going to need need threading so from threading import we just need one thing and that is uppercase th read make sure you see that threading here is lowercase and thread here is uppercase so we are going to import those two things now i need to define two different functions the first function is going to be my box all right like that and then what does my box do well i'm going to print but i'm going to print my box is open open and then what do i want to do i want to sleep for five seconds and then i want to print i want to print my box is closed and then what do i want to do i want to sleep sleep for 5 like that all right so this will just do what i was trying to do earlier but now i'm going to make another function and it's a function because it's not inside of a class right if it's inside of a class it's a method this is not in a class so then i will say def my led like that and then what is this going to do i'm going to say print my led is on and then i'm going to sleep one because what i want to show you is i got one thing that's going really slow and then i've got another thing that's going faster and then i'm going to say print my led is off and then sleep sleep one like that so now i've got two functions now if i just was down here if i was just down here and said my box like that that should work right okay ah i also remember one other thing that's kind of important is once i come in here if i did it this way it's just going to open it and close it and then my led would turn it on and turn it off but i really want these things to keep going right so i'm going to put it in a while loop i'm just going to say while true when is true true true is always true and so this then with what i have done is going to make this an infinite loop and then i will do the same thing here gotta indent these so they will be inside of a while loop and i'll say while true okay now what's the problem if i call my box it's just going to sit and run forever right so let's try that my box is open my box is closed okay what's the problem now it's just going to sit there forever in an infinite loop and i could never even call my led to turn it on and off because it's completely locked up in an infinite loop there so again this is where what we need to do is fire off one of those functions and then fire off the other one and have them running in separate threads okay so we have imported the threading library and we have these two we have these two functions to find and so what we need to do is we need to set up some threads now this isn't starting the thread this is just setting up the thread so i'm going to set up the thread by saying i'm going to have a box thread and that is going to be equal to thread uppercase t okay now understand this box thread you can call that whatever you want you're kind of creating a thread and you're giving it a name the name is box thread it should be something probably related to your box so thread and now we're creating a thread and what do we want to target we want to target the function my box all right target the function my box like that and then i think that should work and now what i want to do is i you guessed it i want to have an led thread and that is going to be equal to thread and then the target equals man i messed up up here didn't i it should be target equals my box and then target equals my led all right so this is saying that you want to run this this mybox function you want to run it as a thread and you're going to call that thread box thread and you're going to want to run my led that function as a thread you're going to call it led thread so i have those two things hooked up started now one thing is is that if you're not careful you could have a program and then you could have a thread and a thread and then you killed the program and you end up with those threads out there kind of existing in the nether world and so you want to kind of when you kill the main program you want it to kind of kill the threads that respond and so if i understand right i would do that by setting box thread dot daemon equals true and then led thread dot daymond is equal to true and this is just setting it up that when you kill things it should kind of kill all the things and not ending up with random processes out there uh going and so now let's see if we can do this we are going to say box thread dot start box tread that would not work well box thread dot start like that and now what do we want to do led thread dot start all right now we're almost there but what you got to see here is if i stop started this it's going to come up in an infinite loop in a separate thread and then it would start this one up here in an infinite loop in a separate strut thread but immediately after that what's going to happen python is going to come here to this step and there's no step there so what's going to happen it's going to be the end of the program the program is going to end and since we set those two daemons up what it's going to do it's going to kill our thread and kill our thread so we need to just pause here so the easiest way to do that is just to say while true when is true true true is always true what do you want to do absolutely nothing and so we're just going to pass and so the program is going to be sitting here and not ending and then up at the top what's going to be happening is those things are going to be running in separate threads could i have really done this without messing something up it's really kind of clear isn't it if i show it to you nice and easy like this okay let's see what happens we're gonna go ahead and try to run this thing my box is open okay guys look at this look at this boom look at this okay you say the box is closed and then led is off on off on off and then boxes open and then on off on off on off and box is closed boom look at this we're threading who's your huckleberry i'm your huckleberry do you see this look at that we are running this thing in threading okay i'm gonna make it a little easier to look at because it was kind of hard so what i'm going to do is i'm going to kind of put a big indent like this and a big indent like this and so it'll be easy to see the difference between my box is open and my box is closed it's going to be a lot easier to see so let's run this thing okay the l my box is open and then on off on off on off and then box is closed and then off on and you see from here on to off this is still working even though this is coming in and interrupting it boom do you see that look at that we are running threads now what i bet is i bet the main program is still going to be its own separate thread and so let's just do something here this is just to kind of play around with it a little bit what if i came in here and on this while true let's just say i said j is equal to zero and then what i could say here is i could say print j all right and then what i could do is i could say j equal j plus one so i'm just going to put a simple counter and then what i'm going to say is sleep 0.1 let's see if you could actually do that inside of these other ones and let's see if that'll work all right so let's run this thing okay look at that so you look at that boom okay so you see the led is on and the led is off and so that counting is not messing up the led on and the led off and then what you can see is is that my box is open and my box is closed so what you can see here is is that now your python program is kind of its own thread and then i have the my box thread and i have the m my led thread and so i kind of got three things that i'm juggling all at the same time and it looks like it is really working okay now a couple of things i did this as simple as possible so that it would be easy for you to understand but what you can also see is really you might want to need to pass a parameter up here because you might need to give it like some data and so how would i pass the parameters because when i am calling it i am just saying target my box and target my led well you might think you would do something like put in delay t like delay t where you passed it a parameter and if you thought that you would be wrong if you thought that you would be wrong and this is the way you have to do it so we're going to come up here and what we're going to want is we're going to want to delay time and so the parameter that you want is delay t and then what you are going to do is you guys can see that okay i'm going to get this and then i'm going to put it in delay t and then i'm going to put it in delay t and then uh here i am going to have i'll just give it a different name delay i'll just give it the same one delay t and then here and when i call it when i call it i can make it different right okay when i call it i can give it a different variable all right so now how do i call it to pass that delay t and so i'm going to say delay box is equal to five and then i am going to say delay led is equal to one and then here what i've got to do is i've got to come up and i've got to give it a comma and then i've got to get out of your way all the way okay so i give it a comma and then i've got to say args for arguments equal and then i've got to pass it the arguments and this argument that i am going to pass it up here is going to be delay box right delay box and now this is the darndest thing if i understand this right if you only have one argument you got to put a comma after it now isn't that crazy that is really crazy let's say if it says okay and now i'm going to have to pass the args here which args are going to be equal to and then this is delay led and then comma and then close so notice that we uh i got this in the wrong spot somehow that ended up over there take that out so target my box target my led and then this closes the args this closes the thread and then this closes the arg and then this closes the thread i think we have to have that comma in there in order for this to work all right so now i'm passing those arguments in let's see if this is going to run boom look at that led is on led is off led is on led is often the box is closed on off on off we did it we did it it worked we passed the parameters into the thread that is really cool now i can't believe that i'm right that you got to put a closing comma there let's take that that that comma out that trailing comma and let's see if it'll run no you see it crashed the threads can you believe that it crashed the thread so i was right you have to put if you're only passing one argument you have to put a comma right if you're passing two arguments you don't have to and so like let's just say that i passed in here red and i passed in here the string blue okay so i'm going to pass it two things red and blue notice no trailing comma and then i will read those in even though i'm not using them and i'll just call it color and then i will read it here as color i'm not using those but i'm just passing them to show you that if you have two arguments you don't have to have a trailing comma okay led is on led is off that's working we're counting and okay so that is one of those crazy little things with the thread library and i just wish i understood it better because usually everything in python is so logical and so clean and makes so much sense but i don't understand why if you're just passing it one argument you have to give it the argument and a comma all right now we show we saw how to do it with zero arguments we saw how to do it with one argument and then with two arguments it kind of behaves in a logical way in a logical way and i have i hate being mr postage stamp down there i i like being live size life size but uh it helps you see the code okay guys so uh i think that that is pretty clear now in a real program what you would do is this first this first function might be like read the gps and then the second function might be like read the pressure sensor and this one is up here constantly measuring the uh measuring the uh gps device this one would be measuring pressure now in that case what you have to do is you have to pass data out of your thread back to the main program and the way you would do that is you would create a class okay you would create a class and then uh so you would you would create a class and then you could just say my dot you could just say self.gps and then you could set that parameter and down in the main program then you could read it go back and watch lesson 19 to remind yourself how to do classes but the way you would have a you would have this thread running inside of a class all right and then you could get the data out pretty easily and in the future when we're doing more complicated programs we'll kind of show you how to do that but for right now you know how threads work so man this has been a great set of lessons you've learned the basic mathematical operators you've learned if statements while loops for loops you've learned how to pickle data how to put data on a file how to read data from a file you have learned about functions you've learned about methods you've learned about classes and you have learned about threads now so you have got a pretty robust python toolkit and i think you know now enough about how python works if you wanted to do something that i didn't train you on you could just just sort of google it and look and see some examples and understand how to do everything that python can do because i think you understand enough now that anything else you need to know you would be able to learn it okay so this is lesson number 20. this this is going to wrap up the phase one of our python lessons the next phase which would be like lesson number 21 but we're going to go back and we're going to start a new series and it is going to be visual python v python and what we're going to start doing is some very very very impressive three-dimensional renderings three-dimensional graphics some simulations we're going to show you how to just create these really awesome three-dimensional simulations three-dimensional visualizations and so we're going to kind of get into 3d graphics the good news is it's really easy and the good news is with what you've learned now you can really do the visualizations well why would you want to do that well maybe you want to hook your python up to an arduino and you want to be measuring temperature but up on the screen you want to see a graphic of a thermometer like a 3d graphic of a thermometer and you want that thermometer adjusting to reflect what the real temperature is so you can start building three-dimensional visuals to present a visualization of the data that you're taking in python so that's what we're going to do next we're going to learn how to do the visual python then after that we're going to learn how to hook your python up to the outside world like hook it up to arduino hook it up to raspberry pi hook it up to another device and then be getting real data into python which you can do things on and then probably after that we're going to learn how to do some graphing and start doing some like more data analysis stuff in python so i hope you guys are enjoying it hope you'll come back next week for the what would be like lesson number 21 but we will call it visual python lesson one okay guys this is paul mcquarter from toptechboy.com if you enjoyed these lessons be sure to give us a thumbs up be sure to subscribe to the channel and ring that bell so you'll get notifications when our new lessons come out and if you like this be sure to share it on your social media because the world needs more coders the world needs more engineers and fewer people sitting around watching silly cat videos paul mccorder from toptechboy.com i will talk to you guys later
Info
Channel: Paul McWhorter
Views: 5,944
Rating: undefined out of 5
Keywords:
Id: XGzASnhr0ZY
Channel Id: undefined
Length: 30min 55sec (1855 seconds)
Published: Wed Jul 07 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.