Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
同時実行数制限付きでループを並列処理する。
package main
import (
"fmt"
"sync"
"time"
)
func main() {
log(-1, -1)
indexes := []int{1, 2, 3, 4, 5, 6, 7}
fmt.Println("sleepなし。順番不定。")
concurLoop(indexes, 3, outputWithoutWait)
fmt.Println("sleepあり。順番に出力。")
concurLoop(indexes, 3, outputWithWait)
waits := []int{3, 2, 5, 2, 8, 1}
fmt.Println("sleepあり。Sleepの短い順番に出力。")
concurLoop(waits, 3, outputWithWait)
}
func outputWithoutWait(index, item int) {
log(index, item)
}
func outputWithWait(index, wait int) {
time.Sleep(time.Duration(wait) * time.Second)
log(index, wait)
}
func log(index, item int) {
fmt.Printf("time:%v\tindex:%d\titem:%v\n", time.Now(), index, item)
}
func concurLoop(array []int, limit int, handler func(int, int)) {
var wg sync.WaitGroup
var semaphore = make(chan struct{}, limit)
for index, item := range array {
wg.Add(1)
semaphore <- struct{}{}
go func(index, item int) {
defer func() {
wg.Done()
<-semaphore
}()
handler(index, item)
}(index, item)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment