Last active
August 29, 2015 13:56
-
-
Save hayajo/9248417 to your computer and use it in GitHub Desktop.
ゴルーチンをプールするパターン
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 ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
func main() { | |
pool := make(chan bool, 3) | |
job := make(chan string) | |
go func() { | |
for { | |
fmt.Println(<-job) | |
} | |
}() | |
var wg sync.WaitGroup | |
for i := 0; i < 10; i++ { | |
pool <- true | |
wg.Add(1) | |
go func(i int) { | |
defer func() { <-pool }() | |
job <- fmt.Sprintf("start job #%d", i) | |
time.Sleep(time.Second) | |
job <- fmt.Sprintf("end job #%d", i) | |
wg.Done() | |
}(i) | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
こんなかんじ