【发布时间】:2021-03-07 20:11:24
【问题描述】:
package main
import (
"fmt"
"time"
)
func Server1(ch chan string) {
time.Sleep(2*time.Second)
ch <- "from Server-1"
}
func Server2(ch chan string) {
time.Sleep(3*time.Second)
ch <- "from Server-2"
}
func main() {
input1 := make(chan string)
input2 := make(chan string)
go Server1(input1)
go Server2(input2)
for {
select {
case s1 := <- input1:
fmt.Printf(s1 + "\n")
case s2 := <- input2:
fmt.Printf(s2 + "\n")
}
}
}
运行上面的代码,得到如下错误
from Server-1
from Server-2
fatal error: all goroutines are asleep - deadlock!
在这个通道选择中,我们有两个线程以不同的时间间隔运行,为什么会死锁?
【问题讨论】:
标签: go concurrency channel goroutine