Select 通道时发生死锁

Hit deadlock when Select channel

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!

在这个通道select中,我们有两个线程运行不同的定时器间隔,为什么会死锁?

你启动了 2 个只在它们的通道上发送一个值的 goroutines,然后它们将终止,所以 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"
    }
}