【问题标题】:Hit deadlock when Select channel选择频道时遇到死锁
【发布时间】: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


    【解决方案1】:

    您启动了 2 个仅在其通道上发送单个值的 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"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-06
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2016-06-07
      • 2021-07-29
      相关资源
      最近更新 更多