Skip to content

Instantly share code, notes, and snippets.

@Sundrique
Created March 6, 2015 11:18
Show Gist options
  • Save Sundrique/c7cfab4295ea67d11446 to your computer and use it in GitHub Desktop.
Save Sundrique/c7cfab4295ea67d11446 to your computer and use it in GitHub Desktop.
Concurrency limit test
package main
import (
"fmt"
"sync"
"time"
)
func spawn(fn func(), count int, limit int) {
limiter := make(chan bool, limit)
spawned := func() {
defer func() { <-limiter }()
fn()
}
go func() {
for i := 0; i < count; i++ {
limiter <- true
go spawned()
}
}()
}
func main() {
count := 10
limit := 3
var wg sync.WaitGroup
wg.Add(count)
concurrentCount := 0
failed := false
var mock = func() {
defer func() {
wg.Done()
concurrentCount--
}()
concurrentCount++
if concurrentCount > limit {
failed = true
}
time.Sleep(100)
}
spawn(mock, count, limit)
wg.Wait()
if failed {
fmt.Println("Test failed");
} else {
fmt.Println("Test passed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment