「让我们一起Golang」怎样出让协程资源和设置可用CPU核心数

前面了解了协程的有关基础知识,了解了CPS并发模型,见识了Golang的百万级并发,下面我们来实现一下出让协程资源和设置可用CPU核心数。

出让协程资源

先看看执行结果:

子协程0 0
子协程0 1
子协程0 2
子协程0 3
子协程0 4
子协程0 5
子协程2 0
子协程2 1
子协程2 2
子协程2 3
子协程2 4
子协程2 5
子协程2 6
子协程2 7
子协程1 0
子协程0 6
子协程0 7
子协程1 1
子协程1 2
子协程1 3
子协程1 4
子协程1 5
子协程1 6
子协程1 7

我们可以看到先是子协程0打印内容,然后字协程2打印内容,然后出现了子协程1打印结果,之后又突然出现了子协程0,然后是子协程1打印结果。

为什么是这样呢?先别急,先看一看代码想一想为什么!

func main() {
	for i:=0;i<3;i++{
		go func(index int) {
			task("子协程"+strconv.Itoa(index))
		}(i)
	}
	time.Sleep(5 * time.Second)
}

func task(name string)  {
	for i:=0;i<8;i++{
		if name == "子协程1"{
            //Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically.
			runtime.Gosched()
		}
		fmt.Println(name,i)
	}
}
runtime.Gosched()
runtime.Gosched()Goschedgoroutinegoroutinegoroutine
runtime.Gosched()runtime.Gosched()

设置可用CPU核心数

我们打开任务管理器,进入“性能”栏目,在CPU处右键选择“将图形更改为”,将“总体利用率”改为“逻辑处理器”。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sd4sR31f-1628902271033)(https://raw.githubusercontent.com/ReganYue/ForPicGo/main/20210801161637.png)]

这里可以看到图片里面的CPU核数为八。

然后我们可用利用GO语言查看电脑CPU的核数。

package main

import (
	"fmt"
	"runtime"
)

func main() {

	fmt.Println("可用CPU核心数为",runtime.NumCPU())
	
    // GOMAXPROCS sets the maximum number of CPUs that can be executing
    // simultaneously and returns the previous setting. If n < 1, it does not
    // change the current setting.
    // The number of logical CPUs on the local machine can be queried with NumCPU.
    // This call will go away when the scheduler improves.
	fmt.Println("设置CPU的可用核数为1,先前的设置为",runtime.GOMAXPROCS(1))
}
runtime.NumCPU()
runtime.GOMAXPROCS(n)