【发布时间】:2020-08-23 11:26:19
【问题描述】:
我正在学习并发,我想实现一个简单的示例,该示例从矩阵中获取行并将值的数组(切片)添加到每一行。
由于我使用的是通道,因此我尝试等待每一行从 goroutine 获得相应的结果。但是,这并不比仅同步执行此操作更好。如何让每一行等待各自的结果,并允许其他行同时计算它们的结果?
https://play.golang.org/p/uCOGwOBeIQL
package main
import "fmt"
/*
Array:
0 1 2 3 4 5 6 7 8 9
+
Matrix:
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
->
Expected result:
1 1 2 3 4 5 6 7 8 9
0 2 2 3 4 5 6 7 8 9
0 1 3 3 4 5 6 7 8 9
0 1 2 4 4 5 6 7 8 9
0 1 2 3 5 5 6 7 8 9
0 1 2 3 4 6 6 7 8 9
0 1 2 3 4 5 7 7 8 9
0 1 2 3 4 5 6 8 8 9
0 1 2 3 4 5 6 7 9 9
0 1 2 3 4 5 6 7 8 10
*/
func main() {
numbers := []int {0,1,2,3,4,5,6,7,8,9}
matrix := [][]int{
{1,0,0,0,0,0,0,0,0,0},
{0,1,0,0,0,0,0,0,0,0},
{0,0,1,0,0,0,0,0,0,0},
{0,0,0,1,0,0,0,0,0,0},
{0,0,0,0,1,0,0,0,0,0},
{0,0,0,0,0,1,0,0,0,0},
{0,0,0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0,0,1},
}
rmatrix := make([][]int, 10)
for i, row := range matrix {
cResult := make(chan []int)
go func(row []int, numbers []int, c chan <- []int) {
c <- addRow(row,numbers)
}(row,numbers,cResult)
//this read from the channel will block until the goroutine sends its result over the channel
rmatrix[i] = <- cResult
}
fmt.Println(rmatrix)
}
func addRow(row []int, numbers []int) []int{
result := make([]int, len(row))
for i,e := range row {
result[i] = e + numbers[i];
}
return result
}
【问题讨论】:
标签: go concurrency goroutine