Last active
January 7, 2020 14:23
-
-
Save u110/980e6e87d56d35d13a9da030a4912af0 to your computer and use it in GitHub Desktop.
同じジョブは同時実行させないようにしたい。 --> channel bufferでblock
This file contains 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 main | |
import ( | |
"log" | |
// "runtime" | |
"sync" | |
"time" | |
) | |
func worker(jobs ...string) <-chan string { | |
var wg sync.WaitGroup | |
receiver := make(chan string) | |
limit := make(map[string](chan int)) | |
for _, i := range jobs { | |
limit[i] = make(chan int, 1) // jobs ごとにchannel作成。 buffer=1にすることで重複させないように | |
} | |
go func() { | |
for _, i := range jobs { | |
wg.Add(1) | |
limit[i] <- 1 | |
go func(i string) { | |
// log.Println("num of goroutine: ", runtime.NumGoroutine()) | |
receiver <- "start: " + i | |
time.Sleep(time.Duration(1) * time.Second) | |
receiver <- "end: " + i | |
wg.Done() | |
<-limit[i] | |
}(i) | |
} | |
wg.Wait() | |
close(receiver) | |
}() | |
return receiver | |
} | |
func main() { | |
log.Println("[START]") | |
defer log.Println("[END]") | |
receiver := worker("pen", "pineapple", "apple", "pen") | |
for { | |
receive, ok := <-receiver | |
if !ok { | |
log.Println("closed.") | |
return | |
} | |
log.Println(receive) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考にさせてもらった記事
http://jxck.hatenablog.com/entry/20130414/1365960707