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

huangapple go评论81阅读模式
英文:

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

问题

我对执行time.Sleep()函数时goroutine的状态很好奇,例如:

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

如果在执行time.Sleep()函数时,goroutine会变成等待状态,那么它如何知道何时将状态更改为就绪状态呢?

我真的很想了解time.Sleep()的底层机制。

英文:

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.

答案1

得分: 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来运行它,以获取所有goroutine的状态。

输出结果:

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 state of the goroutine will be sleep. There is very short program you can test it with:

<!-- language: go -->

package main

import (
	&quot;time&quot;
)

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

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

huangapple
  • 本文由 发表于 2017年2月16日 20:22:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/42273846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定