限制Goroutine并发数量

发布时间:2018-04-07 19:23:26
Go 

正文

package main

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

func main() {
	calcGoroutineNumber()
	c := make(chan bool, 100)
	for i := 0; i < 1000000; i++ {
		c <- true
		go worker(i, c)
	}
}

func worker(i int, c chan bool) {
	time.Sleep(100 * time.Millisecond)
	<-c
}

//定时获取当前的goroutine数量
func calcGoroutineNumber() {
	t := time.Tick(time.Second)
	go func(){
		for {
			select {
			case <-t:
				fmt.Printf("%s, goroutinue number: %d\n", time.Now().Format("15:04:05"), runtime.NumGoroutine())
			}
		}
	}()
}

运行结果

19:21:31, goroutinue number: 102
19:21:32, goroutinue number: 102
19:21:33, goroutinue number: 102
19:21:34, goroutinue number: 102
19:21:35, goroutinue number: 102
...

参考

原文地址:http://zhyoulun.com/post/limit-goroutine-number
转载请注明出处