메뉴 건너뛰기

enjoyTools.net

고루틴 제한

2022.12.20 03:10

꿈돌이 조회 수:41

package main

import (
	"fmt"
	"math/rand"
	"time"
)

// change this for your situation, 20 or 30, 1,000 or 10,000 may be too high
const MAX_CONCURRENT_JOBS = 2

func main() {

	waitChan := make(chan struct{}, MAX_CONCURRENT_JOBS)
	count := 0
	for {
		waitChan <- struct{}{}
		count++
		go func(count int) {
			job(count)
			<-waitChan
		}(count)
	}
}

func job(index int) {
	fmt.Println(index, "begin doing something")
	time.Sleep(time.Duration(rand.Intn(10) * int(time.Second)))
	fmt.Println(index, "done")
}

 

output:

2 begin do something
1 begin do something
2 done
3 begin do something
1 done
4 begin do something
3 done
5 begin do something
5 done
6 begin do something
4 done
7 begin do something
6 done
8 begin do something
8 done
9 begin do something

 

출처: https://calmops.com/golang/golang-limit-total-number-of-goroutines