Skip to content

Instantly share code, notes, and snippets.

@teghnet
Last active November 12, 2020 07:06
Show Gist options
  • Save teghnet/b05924b67d289247fd3259e8b961645b to your computer and use it in GitHub Desktop.
Save teghnet/b05924b67d289247fd3259e8b961645b to your computer and use it in GitHub Desktop.
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")
}
@ariattt
Copy link

ariattt commented Nov 12, 2020

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.

for i := 1; i <= 100; i++ {
        wg.Add(1)
	go worker(i, &wg)
        if I % 5 == 0 { wg.Wait() }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment