dorflv5944 2013-09-28 17:04
浏览 29
已采纳

为什么所有goroutine都陷入僵局?

I am new to Go and also looked abit on the thread "throw: all goroutines are asleep", but I am still wondering why this piece of code deadlock. I believe that I put a number in namesInDir, and should be able to print it afterwards. It seems that I can not add the number to the channel - which confuses me. Anyone that can help me?

type uniprot struct
{
    namesInDir chan int
}


func main(){
u := uniprot{}
u.namesInDir = make(chan int)
u.namesInDir <- 1
//u.readFilenames(os.Args[1])
u.printName()
}   

func (u* uniprot) printName(){
    name := <-u.namesInDir
    fmt.Println(name)
}

I got some suggestion and that I could cheat by buffering the channel. Why is not this working?

u.namesInDir = make(chan int, 100)
u.namesInDir <- 1
for i := 0; i < 10; i++ {
    go u.printName()
}
  • 写回答

1条回答 默认 最新

  • dporb84480 2013-09-28 17:29
    关注

    Buffering the channel works like this.

    A channel with no buffer blocks the sender until the receiver takes the value. In your original example you only have one go routine so all go routines are blocked when you send the integer. A buffer overcomes this. Alternatively run two go routines - one sending and one receiving.

    package main
    
    import "fmt"
    
    type uniprot struct {
        namesInDir chan int
    }
    
    func (u *uniprot) printName() {
        name := <-u.namesInDir
        fmt.Println(name)
    }
    
    func main() {
        u := uniprot{}
        u.namesInDir = make(chan int, 1) // Buffer added here
        u.namesInDir <- 1
        //u.readFilenames(os.Args[1])
        u.printName()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。