2017-02-16 62 views
1

我很好奇夠程的狀態,當我執行time.Sleep()函數,例如:什麼是夠程的狀態時執行time.Sleep()函數

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

如果夠程在執行time.Sleep()函數時會變成等待狀態,那麼goroutine怎麼知道何時將狀態改變爲ready?

我真的很想知道time.Sleep()這裏的底層機制。

+2

https://go.googlesource.com/go/+/master/src/runtime/time.go –

回答

2

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讓所有夠程的狀態。

輸出:

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