1. 首页
  2. 主题
  3. Go问与答

关于遍历chan取出的数据调用函数有误的问题。萌新求教!

AlanLiu0328 · · 1249 次点击
代码如下(不完整):将1-100 分为10组,分别求和再相加。 taskChan 中有10个task,分别存着 1-10,11-20,,,,91-100这10组数字。 可是使用distributeTask1函数时,算出的结果每次都不一样。而使用distributeTask函数则结果正常。另外在t.do()方法中,我打印了每个task的 begin和 end。两次的结果分别如下 ```go package main type task struct { begin int end int result chan int } func (t *task) do(group *sync.WaitGroup) { sum := 0 for i := t.begin; i <= t.end; i++ { sum += i } fmt.Printf("begin:%d,end:%d\n",t.begin,t.end) t.result <- sum group.Done() } func distributeTask1(taskChan chan task, resultChan chan int, wg *sync.WaitGroup) { for t := range taskChan { wg.Add(1) go t.do(wg) } wg.Wait() close(resultChan) } func distributeTask(taskChan chan task, resultChan chan int, wg *sync.WaitGroup) { for t := range taskChan { wg.Add(1) go processTask(t,wg) } wg.Wait() close(resultChan) } func processTask(t task,wg *sync.WaitGroup){ t.do(wg) } ``` ![image.png](https://static.studygolang.com/190704/7dd906a0e33cc766de7d14826ca5949f.png) ![image.png](https://static.studygolang.com/190704/ef6bf527aac9052b8562d844e67f515e.png)
这个跟range 有关,range 出来的是一个地址,每次改变里面的值。你直接用go 的话肯定是不行的,会有多次重复。你第二个函数增加了一次函数调用,使用参数传递的话,相当于赋值给了一个临时变量,所以每次的值都不同了,就不会有这个问题。
#1
更多评论

用户登录

没有账号?注册

今日阅读排行

    加载中

一周阅读排行

    加载中