我正在尝试向某个频道广播一条消息,我只想让它发送 5 条消息。但我总是收到这个错误: 致命错误:所有 goroutine 都在睡觉 - 死锁!
我的代码:
package main
import (
"log"
"sync"
broadcast "github.com/dustin/go-broadcast"
"github.com/pwaller/barrier"
)
//Message boradcasted
type Message struct {
y string
x int
}
var w sync.WaitGroup
var bar barrier.Barrier
func main() {
b := broadcast.NewBroadcaster(100)
w.Add(1)
go workerOne(b)
d := Message{"message :", 0}
go func() {
for i := 0; i < 5; i++ {
d.x = i
log.Printf("Sending %v", d)
b.Submit(d)
}
<-bar.Barrier()
b.Close()
}()
w.Wait()
}
func workerOne(b broadcast.Broadcaster) {
ch := make(chan interface{})
b.Register(ch)
for {
v, ok := <-ch
if ok {
log.Printf("workerOne() reading : %v", v)
} else {
log.Printf("i am here")
close(ch)
b.Unregister(ch)
bar.Fall()
w.Done()
return
}
}
}
输出 :
2019/12/26 20:34:11 Sending {message : 0}
2019/12/26 20:34:11 Sending {message : 1}
2019/12/26 20:34:11 Sending {message : 2}
2019/12/26 20:34:11 Sending {message : 3}
2019/12/26 20:34:11 Sending {message : 4}
2019/12/26 20:34:11 workerOne() reading : {message : 0}
2019/12/26 20:34:11 workerOne() reading : {message : 1}
2019/12/26 20:34:11 workerOne() reading : {message : 2}
2019/12/26 20:34:11 workerOne() reading : {message : 3}
2019/12/26 20:34:11 workerOne() reading : {message : 4}
fatal error: all goroutines are asleep - deadlock!
我尝试了一切,但它不会在workerOne()函数中抛出条件!ok来关闭通道并结束等待,但仍然有相同的错误
慕妹3146593
相关分类