-
-
Save Sundrique/c7cfab4295ea67d11446 to your computer and use it in GitHub Desktop.
Concurrency limit test
This file contains 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 ( | |
"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