Created
October 22, 2018 06:15
-
-
Save jreisinger/17c23653e9752aa3ac935b0b0fe9b60d to your computer and use it in GitHub Desktop.
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 ( | |
| "fmt" | |
| "math/rand" | |
| "sync/atomic" | |
| "time" | |
| ) | |
| var ( | |
| running int64 | |
| ) | |
| func work() { | |
| atomic.AddInt64(&running, 1) | |
| fmt.Printf("[") | |
| time.Sleep(time.Duration(rand.Intn(5)) * time.Second) | |
| fmt.Printf("]") | |
| atomic.AddInt64(&running, -1) | |
| } | |
| func worker(sema chan bool) { | |
| <-sema | |
| work() | |
| sema <- true | |
| } | |
| func main() { | |
| // A buffered channel | |
| sema := make(chan bool, 10) | |
| for i := 0; i < 1000; i++ { | |
| go worker(sema) | |
| } | |
| // Keep maximum 10 workers running at a time | |
| for i := 0; i < cap(sema); i++ { | |
| sema <- true | |
| } | |
| for { | |
| time.Sleep(2 * time.Second) | |
| fmt.Printf("<%d>", running) | |
| } | |
| time.Sleep(30 * time.Second) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment