C# Tutorial 16 Threads

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello internet and welcome to part 16 in my c-sharp video tutorial and this part of this tutorial we're going to focus completely on threads as well as how we can use sleep lock priority passing data to threads and a whole bunch more like always all the code as well as a transcript of this video is available in the description underneath this video and I have a lot to do so let's get into it okay so here we are over Visual Studio or if you're on Mac or Linux you're using Samarin and you're going to make sure that you're going to be using the system threading the guy up here and otherwise nothing here is going to work and then basically with threads they're going to allow you to execute multiple pieces of code that can share resources and data without corrupting it and some important things to remember is that you cannot guarantee when a thread is going to execute you also must lock resources until a thread is done and if you do not do that there is a risk that your data could be corrupted so basically what I'm going to do is I'm just going to create a simple little program just so you can see what a thread looks like so we're going to create a thread so will you just type in a thread t is equal to new thread and I'm going to call for just a whole bunch of ones and zeros to be printed so I'm going to say print one just to do something really simple so it's going to be like a random binary number we're going to be generating here now if you want to start your thread after you create it you just call start on it and I'm going to show you a whole bunch of their different ways you can do it whoops let's change this to T and let's change this to T all right so that looks a little better now what we're going to do underneath here is we're going to create that print 1 method so I'm going to go static void and print 1 just to keep it very simple and then inside of here I'm going to have a for loop inside is equal to 0 and while I is less than 100 or 1 else give 1000 just so we can see a lot of data I plus plus and then this guy down here I'm going to use a shortcut I always want to remind you that just type CW tab tab and here we're just going to say console well to console right so we can keep everything on one page and zero oh no this is going to be the print one part so let's keep it like that and then what we're going to do up here is the main function is actually a thread as well so so that you know that and we come up here and we will go after the start I'll paste that and there just to show you how things will change and up here this is going to print zero on the screen and then this is going to obviously keep the console running so that we can see everything that's going on all right so you're going to so I'm just going to run it you're going to see how this works and you can see that it went and shared times between the main thread and thread you created so it's printed a whole bunch of zeros then printed some ones and then went back and printed some zeros and then some ones and so forth and so on and left unabated that's basically what threads will do if you run multiple threads it's going to shift back and forth and let one thread being the main thread main thread it's going to run for a little bit and it's going to jump down here and it's going to allow this thread right here that's calling print one to execute over and over again until they are both finished ok so that is a simple example of how you can use two threads and now I'm going to jump over and show you an example of sleep and how that can help us ok so now with sleep or the sleep method what that's going to allow us to do is have a thread be suspended for a designated amount of time and I'm just going to show you example here basically what I want to tell my computer to do is to run a program slowly so I want it to print out 0 through 10 and I want it to do it in 1 second increments so that we can see it occur on the screen now what I'm going to do is go for and int is equal to 0 and we're going to continue doing this well I is less than 10 and we'll increment I once again just to keep that nice and simple and then inside of here we are going to come in and do a console.writeline and we're going to print out our number however after we print out the number we want to call thread sleep and tell it to pause for 1000 milliseconds or one second and you're going to see how that is going to affect everything and of course I'm also going to come in here and increment namah each time through so that we can count out from zero it's actually going to be zero to nine and then we can come down here and we can just go and type off something like thread ends so that we know that the thread ends and we're going to get into names and try wordy and checking what threads are running and so forth and so on just want to start off with a very simple example so now let's try to run that and you can see right here it's printing 1 2 3 4 5 so forth and so on with 1 second increments in between them and there you can see thread ends prints okay so pretty cool stuff so that's an example of how we can slow down a thread using sleep and now I want to show you a more elaborate example in which we will lock a thread so that we can keep from contaminating data okay in the same program I'm going to create a new class and I'm going to call it a bank account and the goal here is that we are going to try to protect our bank account from going below 0 we are going to try to keep users from taking more money out than they have in their bank account and we're going to use lock to do that so first I'm going to create this guy and this is going to be the object that we are going to use to lock everything down so that the bank account can't go below 0 and then I'm going to have a balance for my bank account because without that that's not going to make much sense so we can just go and do that and is there anything else I want to do mmm not really okay so let's create a constructor for our bank accounts and this guy is just going to receive a double that's going to be the balance for the bank accounts we'll just go balance like that and whatever balance they pass in we are then going to allow them to withdraw money from their bank accounts so I'm just going to call this withdraw and it's going to be passed some amount that they're going to be able to withdraw from the accounts here I'm going to check that our balance - the amount is not less than 0 and if it is I'm going to come in here and I'm going to say something like sorry and let's print out the balance amount in whoops so that like that in accounts just to give a simple type of message there and then I'm just going to return whatever the balance of the account is just to do something all right otherwise if that doesn't work I'm going to use lock here and what this is going to do is it's going to keep any other threads from coming in here and trying to access all of the code between these curly braces or anything inside of here until each thread is finished so here I'm going to say if balance is greater than or equal to the amounts that they want to withdraw I'm going to gooo a console right here and I'm going to say removed and the dista left in accounts and you close that off and then get the two amounts so I'm going to have the amount that they asked for and then I'm going to get the balance whoops - of the amounts all right so that's also and then of course after I do all of that I'm going to have to change the balance amount and I'm just going to go balance equal to whatever the amount was and subtract the amount they took off of there and then after this let's return the new balance all right pretty simple stuff now one thing it's important I'm going to show you how you're going to be able to pass arguments to threads in a minute but by default you can only point at methods without arguments and also methods that return nothing or have a void for the return amount so what we're going to do is I'm going to say public void and I'll say issue withdraw because I should be withdrawal whatever I'm going to keep it that way and we'll say withdraw and I'm just going to say that every single time somebody takes money out of here they're going to take one dollar out of it and this has given me error messages but going to be using this in a second so we don't have to worry about that okay so basically this is just here so that the thread is going to be able to access this guy up here and in the way that like I said by default threads are not allowed to deal with methods that have arguments or aren't void but like I said I'm going to show you how to pass arguments to threads here in a minute all right so now we're going to come back up inside of our main function we're going to start playing around with this so the very first thing we're going to do is we're going to create a bank account and call that accounts new bank accounts and you're going to get to see how threads sort of like hop around like we did in the first example and I'm going to create a thread array and I'm just going to call this threads a new thread array and we're going to create 15 of these guys inside of here and something that's interesting is the current thread is going to tell you what's current thread is being active and main is the only one that's out there right now so what we're going to do is we're also going to use the name property here to name our main thread main and I'm going to show you in a minute how we can go and get the current name of the thread I didn't want to create 15 threads that are going to call issue withdraw to execute so go in I is equal to zero while I is less than fifteen and increment I here and then this guy basically what I'm going to do is I'm going to create a thread obviously new thread no and then we're going to call thread start and then we're going to call our bank accounts and we're going to call the issue withdraw method inside of it and like I said previously we are not looks like this there we are like I said previously we are not going to be able to call methods that receive attributes or return values I'm then going to get the name or I'm going to set the name for each of these individual threads to whatever the value of I is at the moment as we're cycling through here and then I to add it to my threads array so this is equal to T then after that I'm going to have all of these different threads execute so I'm going to say I is equal to zero and we're going to continue cycling through this as long as it's less than 15 and increment I of course then we're going to go and check if a thread has started or not so I'm going to go thread and you do that by using a property called is a lot so we're just going to output that on the screen just to show you something else you can do with threads and I'm going to go threads I and get the name that's what I assigned up here where did I do it right there we're going to have that print out and then I'm going to check if it's alive by going threads I and by a live I mean is it's currently started or not is live save that then after we do that we're actually going to start the thread so to do that we just issued start on it like this and then we can check if it's alive again so let's just go and copy this and this is going to now we know it's not going to be alive there it will be alive here and we just want to output that to the screen just to see it another thing we can do is we can get the priority of a thread and we're just going to do this outside of here outside of these threads executing so we're going to be doing it with main so here I'm just going to go console so what we can do here to get the priority is just go current priority and get that value right there and we can just call thread on the current thread that is running and every thread is going to have a priority of normal and this is sort of a touchy sort of subject you can change the priorities of your thread but that doesn't guarantee that the highest precedence but that doesn't guarantee that the highest priority is actually going to receive precedence so for the most part it is kind of worthless to play around with priority and kind of dangerous but just so you know you can change the priority to normal which is the default lowest below normal above normal or high so you can play around with that and see what happens and how it affects your code but like I said it's probably better to just ignore it altogether I just wanted to cover it just so that you know what it was all right and then we can come in and say thread and ending and this is going to be main and you might see some crazy stuff that goes on and then we'll just go current thread and get the name right here and console.readline and what's going on down here it's giving me an error oh I see why this guy right here needs to be moved so let's get rid of that right there and then let's put this down here there we are go to our curly brackets in the right place and save it and everything should be good so let's run it see what happens and we can run through here exactly what's going on and you can see thread 0 is alive false and that it is alive thread 1 and so forth and so on you can see how these threads are coming to life and starting to perform actions you can see right here that we removed one dollar nine dollars left in an account thread four is a lot of true and so forth and so on so you can see how these threads become active however they are not executing they're basically staying in line and the reason why they are staying in line is because we are locking the account down right there if we did not do that that would get all kinds of crazy results and go in there and run it and just get rid of the lock and you'll see exactly what happens so basically a lock just protects our count data from going down below zero remove one dollar one dollar left an account remove one dollar zero left in account and then you can see right here sorry zero is in the account and all the other threads are continually trying to pull money out of there but they are not receiving it you're also seeing here that we are using the thread name and outputting it obviously we're using is alive here to check if the thread is currently active or not here you can see is the default priority for the current active thread which is main is normal and you can see right here where we're end or whenever main comes to an end okay so a little bit more elaborate example and very very important that we understand lock and how it protects our data and now like I promised I'm going to show you how to it is possible to pass data to thread okay so you're going to be able to pass arguments to a thread using lambda expressions and we've covered those in detail here in the past and I'm going to show you a quick example of how exactly that's going to work for us so what we're going to do is we're going to create a thread once again equal to new thread and then let's go and create our method here first that we're going to be calling static void and what this is going to do is receive a number and count to that number so we'll go max number and then throw a four loop inside of here so int I is equal to zero we're going to continue looping as long as I is less than or equal to the maximum number passed inside of it and then of course we're going to increment the value of hi and we're going to just print out I inside of here okay so let's save that that's what count two is going to do for us now I'm going to show you up here how we can go and call for that to execute so we're going to go thread and inside of here inside of these parentheses we are then going to point to count two and we're going to say that we want to count to the value of ten with that and then we're going to go to start and execute that and then afterwards I'm going to show you how to actually use a multi-line lambda to have multiple different things execute here so I'm going to go to thread once again and then we've come down to this guy and then have them start once more like that and then like that and then inside of here we're going to cau count two with more values so we'll say count five and then we'll also say count to six I don't know just something and then you're going to watch this because things aren't locked down or sleep isn't used and so forth and so on it's sort of executed crazily but you're going to see the fact that we are able to pass in threads or pass attributes into threads and see them execute and you can see indeed starts executing zero one and then the one two five comes in or zero two five comes in and starts executing and then you can see here is your one two three four five six and then the original thread that was called goes and continues writing out to the screen to ten so let's pay attention here so 0 1 and then it starts v5 let's run it again see if we get the same results just about done and here you see you get different results 0 1 2 3 4 5 6 7 8 and 7 and then the next stored kicks in see it then goes to 5 0 and then the original thread starts up continues to 10 and so forth and so on so it sort of reinforces the fact that you're going to want to use lock and sleep and things like that with threads just to keep your data protected but overall that is just a quick run-through of how threads work and as the series continues I'm going to provide more real-world examples just one to clear up a topic that is sometimes kind of confusing so like always please leave your questions and comments below otherwise until next time
Info
Channel: Derek Banas
Views: 127,647
Rating: undefined out of 5
Keywords: C# Threads, C# Threads Example
Id: hOVSKuFTUiI
Channel Id: undefined
Length: 18min 36sec (1116 seconds)
Published: Wed Mar 01 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.