dsfliu1129 2012-08-08 13:18
浏览 49
已采纳

通道/ Goroutines抛出错误

I'm currently following this tutorial http://www.miek.nl/files/go/20120807-go.pdf and on chapter 7 it discusses channels/goroutines

However the example code is throwing an error for me just after you run it.

package main

import (
    "fmt"
    "time"
)

var c chan int

func ready(w string, sec int) {
    time.Sleep(time.Duration(sec) * time.Second)
    fmt.Println(w, "is ready!")
    c <- 1
}

func main() {
    c := make(chan int)
    go ready("Tea", 2)
    go ready("Coffee", 1)
    fmt.Println("Waiting...")
    <-c
    <-c
}

Here is the output when you execute the code

daniel:go> go run goroutines.go 
Waiting...
Coffee is ready!
Tea is ready!
throw: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /home/daniel/Dropbox/code/go/goroutines.go:21 +0xee

goroutine 2 [syscall]:
created by runtime.main
    /build/buildd/golang-1/src/pkg/runtime/proc.c:221

goroutine 3 [chan send (nil chan)]:
main.ready(0x80bb0d4, 0x3, 0x2, 0x0)
    /home/daniel/Dropbox/code/go/goroutines.go:13 +0xe5
created by main.main
    /home/daniel/Dropbox/code/go/goroutines.go:18 +0x5e

goroutine 4 [chan send (nil chan)]:
main.ready(0x80bba30, 0x6, 0x1, 0x0)
    /home/daniel/Dropbox/code/go/goroutines.go:13 +0xe5
created by main.main
    /home/daniel/Dropbox/code/go/goroutines.go:19 +0x80

goroutine 5 [timer goroutine (idle)]:
created by addtimer
    /build/buildd/golang-1/src/pkg/runtime/ztime_386.c:69
exit status 2

Is there something wrong with my code?

Any help would be appreciated

  • 写回答

1条回答 默认 最新

  • dpca31461 2012-08-08 13:24
    关注

    Yes, just a typo:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    var c chan int
    
    func ready(w string, sec int) {
        time.Sleep(time.Duration(sec) * time.Second)
        fmt.Println(w, "is ready!")
        c <- 1
    }
    
    func main() {
        c = make(chan int) // previously c := make(chan int)
        go ready("Tea", 2)
        go ready("Coffee", 1)
        fmt.Println("Waiting...")
        <-c
        <-c
    }
    

    main() didn't use the global c since it declared a new one.

    Notice that you don't have to make the channel inside main(), make it while declaring it:

    var c = make(chan int)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?