Skip to content

Instantly share code, notes, and snippets.

@jreisinger
Created October 22, 2018 06:15
Show Gist options
  • Select an option

  • Save jreisinger/17c23653e9752aa3ac935b0b0fe9b60d to your computer and use it in GitHub Desktop.

Select an option

Save jreisinger/17c23653e9752aa3ac935b0b0fe9b60d to your computer and use it in GitHub Desktop.
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