Goの並行処理を実際に試す(1)
試して慣れないと不味いと思ってgo-concurrency-patterns
を動作させてみた。
- https://mattn.kaoriya.net/software/lang/go/20131112132831.htm
- https://mattn.kaoriya.net/software/lang/go/20180531104907.htm
- https://github.com/kevchn/go-concurrency-patterns
ここから実際に並行パターンを実際にやってみる
1-2-channel.go
// ends of channel block until both are ready // NOTE: golang supports buffered channels, like mailboxes (no sync)
- このコメントの部分が重要ぽい。
- 準備が整うまでchannnelがblockする
// Kevin Chen (2017) // Patterns from Pike's Google I/O talk, "Go Concurrency Patterns" // Golang channels package main import ( "fmt" "time" ) func main() { ch := make(chan string) go channel_print("Hello", ch) for i := 0; i < 3; i++ { fmt.Println(<-ch) // ends of channel block until both are ready // NOTE: golang supports buffered channels, like mailboxes (no sync) } fmt.Println("Done!") } func channel_print(msg string, ch chan<- string) { for i := 0; ; i++ { ch <- fmt.Sprintf("%s %d", msg, i) time.Sleep(time.Second) } }
1-3-generator.go
- generator pattern
- 処理は別のgoroutineでして結果だけを受け取りたいとかそういうやつかな
- https://medium.com/@thejasbabu/concurrency-patterns-golang-5c5e1bcd0833
- ここみるとiterator作ったりしてる
- わかった
- このgroutineはchannelいるから終わらないんだ
// goroutine is launched inside the called function (more idiomatic) // multiple instances of the generator may be called // returns receive-only channel
// Kevin Chen (2017) // Patterns from Pike's Google I/O talk, "Go Concurrency Patterns" // Golang generator pattern: functions that return channels package main import ( "fmt" "time" ) // goroutine is launched inside the called function (more idiomatic) // multiple instances of the generator may be called // returns receive-only channel func main() { ch := generator("Hello") for i := 0; i < 5; i++ { fmt.Println(<- ch) } } func generator(msg string) <-chan string { // returns receive-only channel ch := make(chan string) go func() { // anonymous goroutine for i := 0; ; i++ { ch <- fmt.Sprintf("%s %d", msg, i) time.Sleep(time.Second) } }() return ch }