简体   繁体   中英

what is the status of goroutine when execute time.Sleep() function

I'm curious about the status of goroutine when I execute the time.Sleep() function, for example:

func main() {
    fmt.Println("before test")
    time.Sleep(time.Second * 2)
    fmt.Println("test")
}

if the goroutine would become the waiting state when execute the time.Sleep() function, how could the goroutine know when to change the state into the ready?

I really want to know the underlying mechanism of time.Sleep() here.

The state of the goroutine will be sleep . There is very short program you can test it with:

package main

import (
    "time"
)

func main() {
    go func() {
        time.Sleep(3 * time.Second)
    }()
    time.Sleep(1 * time.Second)
    panic("foo")
}

Run it like that GOTRACEBACK=1 go run test.go to get the state of all goroutines.

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM