雑なメモ書き

気楽にいきます

Goの並行処理を実際に試す(1)

試して慣れないと不味いと思って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

// 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
}