登录
首页 >  Golang >  Go问答

为何这会导致停滞不前?

来源:stackoverflow

时间:2024-03-05 17:12:22 151浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《为何这会导致停滞不前?》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我不明白为什么下面的代码会导致死锁...有人可以帮助我吗?

什么情况下通道会陷入死锁?我真的很困惑...

下面的代码是按照字母和数字的顺序打印 “12ab34cd56ef78gh910ij1112kl1314mn1516op1718qr1920st2122uv2324wx2526yz2728” 我想使用通道来实现这个目标,但陷入僵局。 删除 numberdone 通道时,一切正常。

import (
    "fmt"
)

func main() {
    AlterPrint()
}

// POINT: communicate between goroutines by channel

func AlterPrint(){
  letter, number := make(chan bool), make(chan bool)
  letterDone := make(chan bool)
  numberDone := make(chan bool)
  go func() {
    i := 1
    for {
      if i > 28 {
          numberDone <- true
          return
      }
      select{
        case <-number: {
          fmt.Print(i)
          i++
          fmt.Print(i)
          i++
          letter <- true
          break
        }
        default: {
          break
        }
      }

    }
  }()

  go func(){
    i := 'A'
    for {
      if i > 'Z' {
        letterDone <- true
        return
      }
      select{
        case <-letter: {
          fmt.Print(string(i))
          i++
          fmt.Print(string(i))
          i++
          number <- true
          break
        }
        default: {
          break
        }
      }
    }
  }()
  number <- true
  <- letterDone
  <- numberDone
}```

I expect the output of "12AB34CD56EF78GH910IJ1112KL1314MN1516OP1718QR1920ST2122UV2324WX2526YZ2728", 
but the actual output is 
goroutine 1 [chan receive]:
main.AlterPrint()
    /tmp/54841538.go:66 +0x183
main.main()
    /tmp/54841538.go:7 +0x14

goroutine 5 [chan send]:
main.AlterPrint.func1(0xc82000c240, 0xc82000c180, 0xc82000c120)
    /tmp/54841538.go:31 +0x25a
created by main.AlterPrint
    /tmp/54841538.go:40 +0xde
exit status 2

解决方案


它实际上应该打印出你所期望的内容,然后陷入僵局。第二个 goroutine 完成所有事情,发送 letterdone 并终止。此时,main 开始在 numberdone 处等待。第一个 goroutine 打印最后两个数字,并在 letter<-true 处开始等待。这就是僵局,此时任何事情都无法向前推进。 尝试使用 fmt.Println 而不是 Print,可能是因为缓冲的原因,它没有打印所有内容。

理论要掌握,实操不能落!以上关于《为何这会导致停滞不前?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>