我目前正在关注本教程http://www.miek.nl/files/go/20120807-go.pdf,并在第7章中讨论了渠道/ goroutines但是,示例代码在运行后立即对我抛出错误。package mainimport ( "fmt" "time")var c chan intfunc 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}这是执行代码时的输出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 +0xeegoroutine 2 [syscall]:created by runtime.main /build/buildd/golang-1/src/pkg/runtime/proc.c:221goroutine 3 [chan send (nil chan)]:main.ready(0x80bb0d4, 0x3, 0x2, 0x0) /home/daniel/Dropbox/code/go/goroutines.go:13 +0xe5created by main.main /home/daniel/Dropbox/code/go/goroutines.go:18 +0x5egoroutine 4 [chan send (nil chan)]:main.ready(0x80bba30, 0x6, 0x1, 0x0) /home/daniel/Dropbox/code/go/goroutines.go:13 +0xe5created by main.main /home/daniel/Dropbox/code/go/goroutines.go:19 +0x80goroutine 5 [timer goroutine (idle)]:created by addtimer /build/buildd/golang-1/src/pkg/runtime/ztime_386.c:69exit status 2我的代码有问题吗?
1 回答
弑天下
TA贡献1818条经验 获得超8个赞
是的,只是一个错字:
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()c因为它声明了一个新的全局变量,所以没有使用它。
请注意,您不必main()在声明以下内容的内部创建频道:
var c = make(chan int)
- 1 回答
- 0 关注
- 205 浏览
添加回答
举报
0/150
提交
取消