Skip to content

Instantly share code, notes, and snippets.

@pawzar

pawzar/main.go

Last active Apr 29, 2020
Embed
What would you like to do?
package main
import (
"log"
"sync"
"time"
)
type SemaphoredWaitGroup struct {
sem chan bool
wg sync.WaitGroup
}
func (s *SemaphoredWaitGroup) Add(delta int) {
s.wg.Add(delta)
s.sem <- true
}
func (s *SemaphoredWaitGroup) Done() {
<-s.sem
s.wg.Done()
}
func (s *SemaphoredWaitGroup) Wait() {
s.wg.Wait()
}
type WaitGroup interface {
Add(delta int)
Done()
Wait()
}
func worker(id int, wg WaitGroup) {
defer wg.Done()
defer log.Printf("#%d done", id)
log.Printf("#%d starting", id)
time.Sleep(time.Second)
}
func main() {
wg := SemaphoredWaitGroup{sem: make(chan bool, 5)}
for i := 1; i <= 100; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
log.Printf("all done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.