golang学习笔记——协程
当主协程退出后子协程也会退出
package main
import (
"fmt"
"time"
)
func main() {
go func() {
i := 0
for {
i++
fmt.Println("son i = ", i)
time.Sleep(time.Second)
}
}()
for i := 0; i < 3; i++ {
fmt.Println("main i = ", i)
time.Sleep(time.Second)
if i == 2 {
break
}
}
}
runtime包
-
runtime.Gosched() 让出当前执行权限
package main
import (
"fmt"
"runtime"
)
func main() {
//设置为单核运行
runtime.GOMAXPROCS(1)
go func() {
for i := 0; i < 5; i++ {
fmt.Println("task i = ", i)
}
}()
for i := 0; i < 2; i++ {
runtime.Gosched()
fmt.Println("main i = ", i)
}
}
-
runtime.Goexit() 终止当前协程
package main
import (
"fmt"
"runtime"
)
func test() {
defer func() {
fmt.Println("dddddddddddddddd")
}()
// return //终止函数
runtime.Goexit() //终止当前协程
fmt.Println("ccccccccccccccccccc")
}
func main() {
go func() {
fmt.Println("aaaaaaaaaaaaaaaa")
test()
fmt.Println("bbbbbbbbbbbbbbb")
}()
for {
}
}
//********输出***********
aaaaaaaaaaaaaaaa
dddddddddddddddd
-
runtime.GOMAXPROCS() 设置执行指令的cpu核数,返回上一次执行设置的cpu核数