douyong8801 2016-02-18 20:44
浏览 45
已采纳

读取并发goroutine中写入的通道时缺少最后一个值

I'm fairly new in Go and I want to run several tasks asynchronously, wait for all of them to be finished and collect their results into a slice.

I was reading a lot of documentation and examples, specially this Nathan LeClaire's post, and came up with something close to what I want to do (see code below). The mechanic is simple:

  • 10 goroutines are triggered and each of them writes a value in a channel.
  • Another goroutine reads the channel and fills the slice.
  • After all these stuff are done, the slice is printed.

However the outcome shows a 9-length slice (values from 0 to 8) and the 10th value (should be 9) seems missing. The program exits just fine and I don't know what is going on. Any hint is appreciated.

Here is a code example to play with http://play.golang.org/p/HUFOZLmCto:

package main

import (
    "fmt"
    "sync"
)

func main() {

    var wg sync.WaitGroup

    n := 10    
    c := make(chan int)

    wg.Add(n)

    for i := 0; i < n; i++ {
        go func(val int) {
            defer wg.Done()
            fmt.Println("Sending value to channel: ", val)
            c <- val
        }(i)
    }

    var array []int

    go func() {
        for val := range c {
            fmt.Println("Recieving from channel: ", val)
            array = append(array, val)
        }
    }()

    wg.Wait()
    fmt.Println("Array: ", array)
}

And this is the outcome:

Sending value to channel:  0
Recieving from channel:  0
Sending value to channel:  1
Recieving from channel:  1
Sending value to channel:  2
Recieving from channel:  2
Sending value to channel:  3
Recieving from channel:  3
Sending value to channel:  4
Recieving from channel:  4
Sending value to channel:  5
Recieving from channel:  5
Sending value to channel:  6
Recieving from channel:  6
Sending value to channel:  7
Recieving from channel:  7
Sending value to channel:  8
Recieving from channel:  8
Sending value to channel:  9
Array:  [0 1 2 3 4 5 6 7 8]     // Note 9 is missing here
  • 写回答

2条回答 默认 最新

  • du27271 2016-02-18 20:51
    关注

    You're exiting before the receiving goroutine has a chance to receive and handle the value. There is also a race condition on the array variable, where main may try to print the array during the appendoperation.

    Note that even though an using unbuffered channel would create a synchronization point between the two loops, and guarantee that the receive loop has the value before wg.Done(), it wouldn't guarantee that the fmt.Println and append happen before main continues.

    One way to arrange this is to put the receive loop in main, and wait on closing the c chan in it's own goroutine:

    go func() {
        wg.Wait()
        close(c)
    }()
    
    for val := range c {
        fmt.Println("Recieving from channel: ", val)
        array = append(array, val)
    }
    

    http://play.golang.org/p/YReTVZtsUv

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳