当前位置:网站首页>Runtime package for golang concurrent programming

Runtime package for golang concurrent programming

2022-06-22 03:23:00 ManNiaoQinFen

runtime The package defines some related to collaborative process management api

runtime.Gosched()

Give up CPU Time slice , Wait for the task to be rescheduled ( The time slice is relatively short )

package main

import (
	"fmt"
)

func show(s string) {
    
	for i := 0; i < 3; i++ {
    
		fmt.Println(s)
	}
}

func main() {
    
	go show("JAVA")
	go show("PHP")
	// Main process 
	for i := 0; i < 2; i++ {
    
		//runtime.Gosched() // The results are different before and after annotation 
		fmt.Println("golang:", i)
	}
}

After comment ( It is also possible to complete the execution )

golang: 0
golang: 1
JAVA

No comment ( Probably all subroutines are completed )

PHP
PHP
PHP
golang: 0
JAVA
JAVA
JAVA
golang: 1

runtime.Goexit()

Exit the current collaboration

package main

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

func show() {
    
	for i := 0; i < 10; i++ {
    
		if i > 5 {
    
			runtime.Goexit() // Before and after use 
		}
		fmt.Printf("i: %v\n", i)
	}
}

func main() {
    
	go show()

	time.Sleep(time.Second)
}

Unused run results

i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9

After using

i: 0
i: 1
i: 2
i: 3
i: 4
i: 5

runtime.GOMAXPROCS

Use the largest cpu Count

package main

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

func a() {
    
	for i := 0; i < 10; i++ {
    
		fmt.Println("a:", i)
	}
}

func b() {
    
	for i := 0; i < 10; i++ {
    
		fmt.Println("b:", i)
	}
}

func main() {
    
	fmt.Printf("runtime.NumCPU(): %v\n", runtime.NumCPU())
	runtime.GOMAXPROCS(2) // It is amended as follows 1 when , Do not alternate , Greater than 1 when , Alternate execution 
	go a()
	go b()
	time.Sleep(time.Second)
}

原网站

版权声明
本文为[ManNiaoQinFen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220308322048.html