课程: Go Practice: Functions

Goroutines and channels - Go教程

课程: Go Practice: Functions

Goroutines and channels

- [Instructor] So far, the functions we've been using have been running consecutively or executing only once the previous function has completed. One of the greatest advantages of Go is its ability to easily and efficiently handle concurrency. Let's explore this further. You can start goroutines which execute a given function by placing the go keyword in front of the invocation. It's that easy. Starting a goroutine is a non-blocking operation so the main goroutine which is executing the main function will not be blocked until the myFunc function completes in its child goroutine. They can be used with both anonymous and named functions. In fact, this example will most likely be broken since the main goroutine will end before any of the implementation code of the myFunc function executes. Instead, we need to use a synchronization mechanism. Channels are a powerful synchronization mechanism which serves the dual purpose of communication and coordination between goroutines. They're initialized using the make function and the data type, which they will be able to communicate between goroutines. They support two main operations: send and receive. These operations block goroutines until they can successfully complete. In this example, I created the shared channel variable. Then I start the goroutine with an anonymous function. While this function runs in its own child goroutine, it has access to all the variables of the main goroutine, or in this case, the shared channel. Once the child goroutine has completed its work, it sends a message to the shared channel. Further down, the main goroutine is blocked until it's able to receive a message from the child goroutine that it has completed. This simple example demonstrates the basic usage of channels for both sending information between goroutines and synchronizing them to ensure they run and complete as expected. You'll practice your concurrency skills by calculating the variance value from the previous challenge in a concurrent way. Since the calculation of each item in the sum is done independently, you can calculate them separately in their own goroutines. This can bring great performance benefits for large data, or in the case that the applied function is computationally intensive. On line 14, I've declared an empty CalculateVariance function as the starting point. You can iterate over your solution from the previous challenge or you can write the concurrent solution from scratch. Remember to use channels, not shared variables, to pass the calculation results between goroutines. Good luck.

内容