Solution: Goroutines
- [Instructor] I've opted to change the implementation of the previous challenge. In this case, this has saved me time, but it can sometimes be easier to write concurrent code from scratch instead of modifying existing code. On line 24, I've created a results channel inside the scope of the sum function. It's initialized as a buffer channel, which allocates the same capacity for saving results as the numbers slice. This will allow our goroutines to immediately write the results without being blocked. Next, on lines 26 to 28, I created a goroutine which takes a single int parameter, I. This parameter is a placeholder for the number I'm currently processing. Inside the goroutine on line 27, I send the function return value to the results channel. Finally, I invoke the anonymous function with the num variable as a parameter. While the goroutine does have access to the num variable in the for loop, this number will change while the goroutine is executing, so it must be passed as a parameter, which allows me to copy the value of the variable at the time of invocation. Once all the numbers in the numbers slice have been sent for concurrent processing, I need to collect the results again to compute the sum. I am expecting as many processed results as entries in the numbers slice. On lines 30 to 32, I create a for loop which runs from zero to the length of the slice inside the loop. I receive each computed result from the result channel and add it to the sum variable s. That's all the code we need in order to modify our sum function to make use of goroutines and concurrent processing. Any users of the CalculateVariance function are also not aware of its internal implementation complexities that are now using goroutines and channels. Let's try out our function using the Test My Code button. The challenge returns the same expected values as challenge three.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。