我有一个简单的 go 程序,它有 2 个消费者通道同时从一个生产者读取,如下所示:
package main
import "fmt"
func main() {
producer := make(chan int)
wait := make(chan int)
go func() {
for i := 0; i < 1000; i++ {
producer <- i
}
close(producer)
wait <- 1
}()
go func() {
count := 0
for _ = range producer {
count++
}
fmt.Printf("Consumer 1: %i\n", count)
}()
go func() {
count := 0
for _ = range producer {
count++
}
fmt.Printf("Consumer 2: %i\n", count)
}()
<-wait
}
我期待两个消费者获得相同数量的数据或至少几乎相等。然而结果总是:
Consumer 1: %!i(int=667)
Consumer 2: %!i(int=333)
它在多次运行之间保持不变。谁能为我解释这种行为?
环境:
go version go1.4.2 darwin/amd64
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/usr/local/go/:/Users/victor/Dropbox/projects/go/"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.4.2/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.4.2/libexec/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1"
料青山看我应如是
相关分类