Last active
July 10, 2023 14:04
-
-
Save debdutdeb/9202eaa665e22d4da6bc9bbb376a8bdd to your computer and use it in GitHub Desktop.
go max concurrent example
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
//https://goplay.tools/snippet/gYQ3zCEsjUV | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
batch := 5 | |
waits := []int{10, 23, 11, 15, 16, 13, 19, 12, 10, 22, 12} | |
errChan := make(chan error) | |
done := make(chan struct{}) | |
fmt.Printf("wait times: %#v\n", waits) | |
go func() { | |
for i, w := range waits { | |
if i >= batch { | |
<-errChan | |
} | |
go foo(w, errChan) | |
} | |
done <- struct{}{} | |
}() | |
<-done | |
} | |
func foo(i int, errChan chan error) { | |
fmt.Printf("starting %d\n", i) | |
time.Sleep(time.Duration(i) * time.Second) | |
fmt.Printf("running completed %d\n", i) | |
errChan <- nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment