package main
import "fmt"
import "runtime"
import "time"
func check(id int) {
fmt.Println("Checked", id)
<-time.After(time.Duration(id)*time.Millisecond)
fmt.Println("Woke up", id)
}
func main() {
defer runtime.Goexit()
for i := 0; i <= 10; i++ {
fmt.Println("Called with", i)
go check(i)
}
fmt.Println("Done for")
}
我对 Go 很陌生,所以任何指针都会很棒。我将如何调试这样的事情?
您可以运行代码片段http://play.golang.org/p/SCr8TZXQUE
更新:这在操场上没有线路 <-time.After(time.Duration(id)*time.Millisecond)
,我想知道为什么?(正如@dystroy 提到的,这可能是因为操场处理时间的方式)
当我在本地尝试时,这是输出:
Called with 0
Called with 1
Checked 0
Called with 2
Checked 1
Called with 3
Checked 2
Called with 4
Woke up 0
Checked 3
Called with 5
Checked 4
Called with 6
Checked 5
Called with 7
Checked 6
Called with 8
Checked 7
Called with 9
Checked 8
Called with 10
Checked 9
Woke up 1
Done for
Checked 10
Woke up 2
Woke up 3
Woke up 4
Woke up 5
Woke up 6
Woke up 7
Woke up 8
Woke up 9
Woke up 10
throw: all goroutines are asleep - deadlock!
goroutine 2 [syscall]:
created by runtime.main
/tmp/bindist046461602/go/src/pkg/runtime/proc.c:221
goroutine 5 [timer goroutine (idle)]:
created by addtimer
/tmp/bindist046461602/go/src/pkg/runtime/ztime_amd64.c:69
exit status 2
所有的 goroutine 都完成了,但无论如何都会引发死锁。我应该注意,如果使用计时器并不重要,无论哪种方式都会死锁。