Created
January 22, 2021 10:18
-
-
Save bancek/0d7fd266e9b994cc688623d4a6c4eb18 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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