zl程序教程

您现在的位置是:首页 >  其他

当前栏目

go语言限制Goroutine数量

2023-04-18 16:14:04 时间
package main
 
import (
	_ "ORMTest/routers"
	"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
", runtime.NumGoroutine())
}
 
func worker(i int, c chan bool) {
	//fmt.Println("worker", i)
	time.Sleep(100 * time.Microsecond)
	<-c
}