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条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站