go语言限制Goroutine数量

前端之家收集整理的这篇文章主要介绍了go语言限制Goroutine数量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
 
import (
	"fmt"
	"runtime"
	"time"
)
 
func main() {
	runtime.GOMAXPROCS(runtime.Numcpu())
	c := make(chan bool,100)
	t := time.Tick(time.Second)
 
	go func() {
		for {
			select {
			case <-t:
				watching()
			}
		}
	}()
 
	for i := 0; i < 10000000; i++ {
		c <- true
		go worker(i,c)
	}
 
	fmt.Println("Done")
}
 
func watching() {
	fmt.Printf("NumGoroutine: %d\n",runtime.NumGoroutine())
}
 
func worker(i int,c chan bool) {
	//fmt.Println("worker",i)
	time.Sleep(100 * time.Microsecond)
	<-c
}
原文链接:https://www.f2er.com/go/191076.html

猜你在找的Go相关文章