Last active
November 12, 2020 07:06
-
-
Save teghnet/b05924b67d289247fd3259e8b961645b to your computer and use it in GitHub Desktop.
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
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
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.