duanmianxue2687 2017-03-28 04:21
浏览 59

golang缓冲通道意外结果

package main
import (
    "time"
    "runtime"
)

var c = make(chan int, 2)

func main() {
  go worker(1)
  for i := 0; i < 30; i++ {
    go func() {
            // k := i   make a local copy not make any difference
            c <- i
    }()
  }
  time.Sleep(100* time.Second)
}

func worker(id int) {
  for {
    a := <-c
    println(a, runtime.NumGoroutine())
    time.Sleep(time.Second)
  }
}

the output is unpredictable, sometimes like below.

7 9
13 29
13 28
13 27
13 26
13 25
13 24
13 23
16 22
16 21
17 20
19 19
21 18
21 17
23 16
25 15
26 14
26 13
26 12
26 11
26 10
26 9
26 8
26 7
27 6
27 5
13 4
28 3
30 2
30 2

I know sender will block if the buffer channel is full, and when channel is available the sender can continue.

  1. why output is not constant output 0-29? how to make it??
  2. how variable/local variable store in goroutine??
  3. if lots of senders are blocked, are they waked up by FIFO order??
  • 写回答

2条回答 默认 最新

  • dongliu8542 2017-03-28 08:48
    关注

    Output is not constant because different goroutines share same local variable i. If you uncomment your line and move it right before the goruoutine call, you'll see constant output 0-29. The better way is to move i variable to goroutine function arguments.

    Wake up order is not specified in specs. You should consider it as a random one.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题