Goroutines
- [Instructor] Go supports multi-threaded programming with built-in primitives that you'll find makes reasoning about such programs quite approachable. Let's start with the star of the show. Goroutines. Goroutines are lightweight threads managed by the Go runtime. Go's thread scheduler's superpower is its ability to schedule multiple Goroutines to run across a comparatively smaller number of operating system threads, thereby making very efficient use of those OS level threads across the multiple CPU cores available on today's machines. It's not uncommon to have programs running thousands of Goroutines within the same program. Okay, let's see some in action. We have here a sum function that takes in a slice of ints, calculates their sum and prints out the results. Pretty simple. Let's run the program. And here we are. Now let's run this function in its own thread by simply putting the keyword go in front of it. Let's run the program again. And we get nothing back. Surprised? That's because after our main thread fires off a separate thread to run sum in the main thread simply continues along and does not wait for that new thread to finish. We can illustrate this simply by forcing our main thread to sleep for just a few milliseconds. Enough time to let the other Goroutine finish. We'll add a time.sleep and a hundred milliseconds should be enough. Let's run the program again. And there you go. This time we got our results back. So far so good. But using sleep statements in our code to force Goroutines to wait on each other is not practical. We need a way to have these Goroutines communicate with each other. That's where channels come in.