我对GoLang世界很陌生,并且正在尝试goroutines/频道。据我所知,渠道是戈鲁丁之间的双向沟通方式。如果我们创建一个长度为 0 的通道,它应该是一个同步通道,它表示除非某些 goroutine(即使用者)从通道读取值,否则生产者将无法前进。
我尝试了下面的示例来测试这一点,但我没有得到预期的结果。
package main
import (
"fmt"
"time"
)
var done = make(chan bool)
var msgs = make(chan int)
func produce() {
for i := 0; i < 40; i++ {
//fmt.Println("sending")
fmt.Println("Produced: ", i)
msgs <- i
//fmt.Println("Channel size is: ", len(msgs))
}
fmt.Println("Before closing channel")
close(msgs)
fmt.Println("Before passing true to done")
}
func consume() {
for msg := range msgs {
//fmt.Println("Going to take one, Channel size is: ", len(msgs))
fmt.Println("Consumer: ", msg)
time.Sleep(100 * time.Millisecond)
}
done <- true
}
func main() {
go produce()
go consume()
<-done
fmt.Println("After calling DONE")
}
输出:
Produced: 0
Produced: 1
Consumer: 0
Consumer: 1
Produced: 2
Consumer: 2
...
我期望输出
Produced: 0
Consumer: 0
Produced: 1
Consumer: 1
Produced: 2
Consumer: 2
请帮我在这里指出我做错了什么?
子衿沉夜
相关分类