Created
March 25, 2018 01:03
-
-
Save bojand/477694202d0c0a1f89e0b4e4141ecfb6 to your computer and use it in GitHub Desktop.
goroutine throttling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"sync" | |
"time" | |
) | |
const tasksPerSecond = 1 | |
func main() { | |
totalTasks := 100 | |
concurrency := 5 | |
var wg sync.WaitGroup | |
wg.Add(concurrency) | |
log.Println("Starting ...") | |
for i := 0; i < concurrency; i++ { | |
go func(count int) { | |
runWorker(count, totalTasks/concurrency) | |
wg.Done() | |
}(i) | |
} | |
wg.Wait() | |
log.Println("... Done") | |
} | |
func runWorker(tn, n int) { | |
log.Printf("task: %d n: %d\n", tn, n) | |
var throttle <-chan time.Time | |
if tasksPerSecond > 0 { | |
throttle = time.Tick(time.Duration(1e6/(tasksPerSecond)) * time.Microsecond) | |
} | |
for i := 0; i < n; i++ { | |
if tasksPerSecond > 0 { | |
<-throttle | |
} | |
log.Printf("doing task %d\n", tn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment