0
点赞
收藏
分享

微信扫一扫

go runtime包

书写经典 2022-07-27 阅读 77

 

  

  • Gosched:让当前协程让出cpu以让其他协程运行,它不会挂起当前协程,因此当前协程未来会继续执行
  • NumCPU:返回当前系统的CPU核数量
  • GOMAXPROCS:设置最大的可同时使用的CPU核数
  • Goexit:退出当前goroutine(但是defer语句会照常执行)
  • NumGoroutine:返回真该执行和排队的任务总数
  • GOOS:目标操作系统
  • GOROOT:返回本机的GO路径

 

    1. runtime.Gosched() 让出当前cpu 时间片

 

import (
"fmt"
"runtime"
)

func main() {
go func(s string) {
for i := 0; i < 2; i++ {
fmt.Println(s)
}
}("world")

for i := 0; i < 2; i++ {
// 用于让出CPU时间片,让出当前goroutine的执行权限,调度器安排其它等待的任务运行,

runtime.Gosched()
fmt.Println("hello")
}
}

2. runtime.Goexit() 退出当前协程

 

package main

import (
"fmt"
"runtime"
"time"
)

func test1() {
defer fmt.Println("cc")

//return //终止此函数
runtime.Goexit() //终止所在的协程
fmt.Println("ddd")
}

func main() {

//创建新建的协程
go func() {
fmt.Println("aaaaaa")

//调用了别的函数
test1()

fmt.Println("bbbbb")
}()

//防止主协程执行完毕
time.Sleep(100*time.Second)
}

  



举报

相关推荐

0 条评论