Skip to content

Instantly share code, notes, and snippets.

@bancek
Created January 22, 2021 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bancek/0d7fd266e9b994cc688623d4a6c4eb18 to your computer and use it in GitHub Desktop.
Save bancek/0d7fd266e9b994cc688623d4a6c4eb18 to your computer and use it in GitHub Desktop.
package concurrently
import (
"sync"
"sync/atomic"
)
type Task interface {
Do()
}
type TaskFunc func()
func (t TaskFunc) Do() {
t()
}
func Concurrently(concurrency int, tasks []Task) {
tasksLen := int32(len(tasks))
var taskIdx int32 = -1
var wg sync.WaitGroup
wg.Add(len(tasks))
for i := 0; i < concurrency; i++ {
go func() {
for {
// this approach is 3x faster than using channels
i := atomic.AddInt32(&taskIdx, 1)
if i >= tasksLen {
return
}
tasks[i].Do()
wg.Done()
}
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment