gpt4 book ai didi

go - 选择 channel 时遇到死锁

转载 作者:行者123 更新时间:2023-12-03 10:07:37 25 4
gpt4 key购买 nike

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!
在这个 channel 选择中,我们有两个线程以不同的定时器间隔运行,为什么会死锁?

最佳答案

您启动 2 个仅在其 channel 上发送单个值的 goroutine,然后它们将终止,因此 main功能将被单独留在那里。这就是僵局的原因。
如果修改 Server1()Server2()无休止地发送值,不会陷入僵局:

func Server1(ch chan string) {
for {
time.Sleep(2 * time.Second)
ch <- "from Server-1"
}
}

func Server2(ch chan string) {
for {
time.Sleep(3 * time.Second)
ch <- "from Server-2"
}
}

关于go - 选择 channel 时遇到死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64996760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com