我正在try 使用缓冲通道在Golang创建生产者-消费者消息队列系统.这是我的实现.
package main
import "fmt"
type MessageQueue struct {
storage chan int
count int
}
var done = make(chan bool)
func NewMessageQueue(count int) *MessageQueue {
ret := &MessageQueue{
count: count,
storage: make(chan int, count),
}
return ret
}
func (m *MessageQueue) Produce() {
for i := 0; i < m.count; i++ {
m.storage <- i + 1
}
done <- true
}
func (m *MessageQueue) Consume(f func(int) int) {
for each := range m.storage {
fmt.Printf("%d ", f(each))
}
}
func main() {
op1 := func(a int) int {
return a * a
}
msq := NewMessageQueue(10)
go msq.Produce()
go msq.Consume(op1)
<-done
}
但不幸的是,当我运行go run main.go
时,我无法获得输出,但是为了判断是否存在任何竞争条件,当我try go run -race main.go
时,我确实获得了输出.我无法理解为什么会发生这种事.有人能帮我吗?