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
This comment has been minimized.
I read your post about semaphored wait group (https://www.tegh.net/2020/04/29/semaphored-wait-group/) but we can just implement it without interfacing a library type. We can do this instead.