go语言之进阶篇runtime包中 Gosched Goexit GOMAXPROCS的使用
一、runtime包
1、Gosched的使用
runtime.Gosched() 用于让出CPU时间片,让出当前goroutine的执行权限,调度器安排其他等待的任务运行,并在下次某个时候从该位置恢复执行。
这就像跑接力赛,A跑了一会碰到代码runtime.Gosched() 就把接力棒交给B了,A歇着了,B继续跑。
示例:
package main import ( "fmt" "runtime" ) func main() { go func() { for i := 0; i < 5; i++ { fmt.Println("go") } }() for i := 0; i < 4; i++ { //让出时间片,先让别的协议执行,它执行完,再回来执行此协程 runtime.Gosched() fmt.Println("hello") } }
执行结果:
go go go go go hello hello hello hello
2、Goexit的使用(终止协程)
示例:
package main import ( "fmt" "runtime" ) func test() { defer fmt.Println("ccccccccccccc") //return //终止此函数 runtime.Goexit() //终止所在的协程 fmt.Println("dddddddddddddddddddddd") } func main() { //创建新建的协程 go func() { fmt.Println("aaaaaaaaaaaaaaaaaa") //调用了别的函数 test() fmt.Println("bbbbbbbbbbbbbbbbbbb") }() //别忘了() //特地写一个死循环,目的不让主协程结束 for { } }
执行结果:
aaaaaaaaaaaaaaaaaa ccccccccccccc
3、GOMAXPROCS的使用
示例:
package main import ( "fmt" "runtime" ) func main() { //n := runtime.GOMAXPROCS(1) //指定以1核运算 n := runtime.GOMAXPROCS(4) //指定以4核运算 fmt.Println("n = ", n) for { go fmt.Print(1) fmt.Print(0) } }
执行结果:
00000000000000000000000000000000000000000000000000000000000000000000000000011111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111110000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111100000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000001111111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111100000000000000000000000000000000000000000000000000000000000000000000