go语言限制Goroutine数量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SunboyJohn690905084/article/details/82804344
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\n", runtime.NumGoroutine())
}

func worker(i int, c chan bool) {
	//fmt.Println("worker", i)
	time.Sleep(100 * time.Microsecond)
	<-c
}

猜你喜欢

转载自blog.csdn.net/SunboyJohn690905084/article/details/82804344