我正在尝试按照 Go Concurrency 书实现桥接模式
func bridge_impl() {
done := make(chan interface{})
defer close(done)
var wg sync.WaitGroup
bridge := func(
done <-chan interface{},
chanStream <-chan <-chan interface{},
) <-chan interface{} {
valStream := make(chan interface{})
go func() {
wg.Add(1)
defer close(valStream)
for {
var stream <-chan interface{}
select {
case maybeStream, ok := <-chanStream:
fmt.Println("works")
if ok == false {
return
}
stream = maybeStream
case <-done:
return
}
for val := range stream {
select {
case valStream <- val:
case <-done:
}
}
}
}()
return valStream
}
genVals := func() <-chan <-chan interface{} {
chanStream := make(chan (<-chan interface{}))
go func() {
wg.Add(1)
defer close(chanStream)
for i := 0; i < 10; i++ {
stream := make(chan interface{})
stream <- i
close(stream)
chanStream <- stream
}
}()
return chanStream
}
for v := range bridge(done, genVals()) {
fmt.Printf("%v ", v)
}
wg.Wait()
}
但是我一开始收到一个死锁错误all goroutines are asleep - deadlock!,我想我应该添加一个等待组,即使它没有在书中的例子中实现,但我最终还是遇到了同样的错误