当我执行time.Sleep()函数时,我对goroutine的状态感到好奇,例如:
func main() {
fmt.Println("before test")
time.Sleep(time.Second * 2)
fmt.Println("test")
}
如果执行time.Sleep()函数时goroutine将成为等待状态,goroutine怎么知道何时将状态更改为准备好?
我真的想知道time.Sleep()的基本机制。
答案 0 :(得分:3)
goroutine的状态为sleep
。有一个很短的程序,你可以测试它:
package main
import (
"time"
)
func main() {
go func() {
time.Sleep(3 * time.Second)
}()
time.Sleep(1 * time.Second)
panic("foo")
}
像GOTRACEBACK=1 go run test.go
一样运行它以获得所有goroutines的状态。
输出:
panic: foo
goroutine 1 [running]:
panic(0x45afa0, 0xc42006c000)
/usr/local/go/src/runtime/panic.go:500 +0x1a1
main.main()
/home/user/path/test.go:12 +0x96
goroutine 4 [sleep]:
time.Sleep(0xb2d05e00)
/usr/local/go/src/runtime/time.go:59 +0xe1
main.main.func1()
/home/user/path/test.go:9 +0x2b
created by main.main
/home/user/path/test.go:10 +0x39
exit status 2