Skip to content

Instantly share code, notes, and snippets.

@sugilog
Created December 2, 2016 05:36
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 sugilog/8dad9d5c92660612585ae2e764bdd7db to your computer and use it in GitHub Desktop.
Save sugilog/8dad9d5c92660612585ae2e764bdd7db to your computer and use it in GitHub Desktop.
同時実行数制限付きでループを並列処理する。
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