package main
import("fmt""runtime")funcmain(){gofunc(){for{
fmt.Println("子协程")}}()for{//主协程
runtime.Gosched()// 出让当前 cpu 时间片,由子协程抢占
fmt.Println("主协程")}}
runtime.Goexit() 退出go程
package main
import("fmt""runtime")functest(){defer fmt.Println("c")//return
runtime.Goexit()// 退出当前go程,test是go程的子函数,Goexit是退出整个go程defer fmt.Println("d")}funcmain(){gofunc(){defer fmt.Println("a")test()
fmt.Println("b")}()for{}}
runtime.GOMAXPROCS(1) 设置cpu核数
package main
import("fmt""runtime")funcmain(){
n := runtime.GOMAXPROCS(1)//将cpu设置为 单核,返回值是上一次设置的值,而这里上一次设置的值是默认值
fmt.Println("n = ", n)for{go fmt.Print(0)// 子go 程
fmt.Print(1)// 主 go 程}}