We're back with the second video of this section go routines in the previous video we learned what concurrency
is.
In this video we'll create our first go routine and then see how to launch anonymous functions as new
guy routines.
We'll also learn to use the weight groups in go.
We achieve concurrency by working with go routines like processes that run applications in a computer
concurrently.
In fact the main loop of go could be considered a go routine to go routines are used in places where
we would use actors.
They execute some logic or die or keep looping if necessary but go routines are not threads we can launch
thousands of concurrent go routines even millions they're incredibly cheap with a small growth stack
we'll use go routines to execute code that we want to work concurrently.
For example three calls to three services to compose a response can be designed concurrently with three
go routines to do the service calls potentially in parallel and a fourth go routine to receive them
and compose the response.
The point here is that if we have a computer with four cause we could potentially run this service corps
in parallel but if we use a one core computer the design will still be correct and the calls will be
executed concurrently in only one core by designing concurrent applications.
We don't need to worry about parallel execution returning to the bike analogy.
We were pushing the pedals of the bike with our two legs that's to go routines concurrently pushing
the pedals.
When we use a tandem we had a total of four go routines possibly working in parallel but we also have
two hands to handle the front and rear brakes.
That's a total of eight go routines for our two threads bike actually we don't pedal when we break and
we don't break and we pedal.
That's a correct concurrent design.
Our nervous system transports the information about when to stop pedaling and when to start braking
in go our nervous system is composed of channels.
We'll see them after playing a bit with go routines first.
Enough of the explanations now let's get our hands dirty for our first go routine we'll print the message
Hallowell world in a go routine let's start right now I've already created a file and named it go routine
where we first need to add the main package and a simple function with the print command running this
small snippet of code will simply output hello world in the console so let's say this file and move
on to the terminal
type the command Go run go routines dot go and here's the output which we wrote in the print statement
Not impressive at all to run it in a new go routine we just need to add the keyword go at the beginning
of the call to the function let's try this get back to the code file and go over here with this simple
word we're telling go to start a new go routine running the contents of the hello world function now
again save the file and navigate to a terminal notice run it what it printed nothing.
Why is that things get complicated when you start to deal with concurrent applications.
The problem is that the main function finishes before he hello world function gets executed let's go
back to the code file and analyze it step by step the main function starts and schedules a new go routine
that will execute me hello world function but the function isn't executed when the function finishes
it's still in the scheduling process.
So our main problem is that the main function has to wait for the go routine to be executed before finishing
so let's pause for a second to give some room to the go routine for this out to the main function time
dot sleep
and in parentheses time dot second now the time dot sleep function effectively sleeps the main go routine
for one second before continuing and exiting if we run this now we must get the message say the file
and get back to a terminal run the go routine again whoops we need to import the package time let's
go back to the code file and do it import in inverted commas time cool.
Let's say the file and run it again.
We again get the output.
Hello world.
I suppose you must have noticed by now the small gap of time where the program is freezing before finishing.
This is the function for sleeping if you're doing a lot of tasks you might want to raise the waiting
time to whatever you want.
Just remember that in any application the main function cannot finish before the rest of the go routines.
Now let's see how we can launch anonymous functions as new go routines we've defined the hello world
function so that it can be launched with a different go routine.
This is not strictly necessary because you can launch snippets of code directly in the function scope
as we did in this piece of code.
This is also valid we've used an anonymous function and we've launched and you go routine using the
go keyword.
Take a closer look at the closing braces of the function.
They're followed by opening and closing parentheses indicating the execution of the function.
We can also pass data to anonymous functions.
Let me show you how to do this.
You need to add message with the keyword string in the Go function and pass the message to the print.
L end function after the brace brackets of the go function at the message in double quotes as Hello
World.
This is also valid.
We have defined an anonymous function that received a string which then printed the received string.
When we called the function in a different go routine we passed the message we wanted to print.
In this sense.
Another example would also be valid.
Let me show you this one.
It's looking a little messy.
Let me ident it probably okay.
In this case we've defined the function within the scope of our main function and stored in a variable
called message printed.
Now we can concurrently print as many messages as we want by using the message print a string signature
it's on to say the file and run the code moved to the terminal and run the command.
Go run go routines Dok Go we've just scratched the surface of concurrent programming and go but we can
already see that it can be quite powerful but we definitely have to do something with that sleeping
period wait groups can help us with this problem weight group comes in the synchronization package also
called as the sync package to help us synchronize many concurrent go with T.
It works very easily every time we have to wait for one guy waiting to finish we add one to the group
and once all of them are added we asked the group to wait when the guy routine finishes it says done
and the wait group will take one from the group let's add the code for this.
This is the simplest possible example of a weight group.
First we created a variable to hold it called the weight variable next.
Before launching the new go routine we say to the weight group hey you have to wait for one thing to
finish by using the white dot add one method.
Now we can launch the one that the weight group has to wait for.
Which in this case is the previous go routine that prints hello world and so is done by using the white
dot done method at the end of the go routine.
Finally we indicate to the weight group to wait we have to remember that the function white dot Waits
was probably executed before the go routine now save the file and run the code again.
Go run weight group dot go now it just weights the necessary time and not one millisecond more before
exiting the application remember that when we use the add value method we add entities to the weight
group and when we used a done method we subtract one actually the add function takes it down today.
Now let me show you another code which is equivalent to the previous one.
Open the White grouped dot file and let let's modify the line where we wrote the white dot done method.
Now we can change it to white dot add in parentheses the value is minus 1 in this case we added 1 before
launching the go routine and we added minus 1 that is subtracted 1 at the end of it if we know in advance
how many go routines we're going to launch we can also call the add method just once let me show you
another piece of code which you can use let's replace these lines in this example we're going to create
five go routines are stated in the Go routines variable we know it's an advance so we can simply add
them all to the weight group we're then going to launch the same amount of Go routine variables by using
a for loop every time one go routine finishes it calls the done method of the weight group that is effectively
waiting at the end of the main loop again in this case the code reaches the end of the main function
before all go routines are launched if any and the weight group makes the execution of the main flow
wait until all done messages are called say the file and let's run this small program go run weights
group Dok Go we haven't mentioned it before but we passed the iteration index to each go routine as
the parameter go routine I.D. to print it with a message Hello go routines you might also have noticed
that they go routines aren't executed in order Orson in this video we've worked we've got routines in
the next video we'll learn to use callbacks and go.