【GO】Golang ~ 並列プログラミング(Goルーチン/チャンネル) ~

■ はじめに

https://dk521123.hatenablog.com/entry/2020/04/12/145237
https://dk521123.hatenablog.com/entry/2020/04/03/000000
https://dk521123.hatenablog.com/entry/2020/04/05/000000

の続き。

Go言語における気になる文法事項で、以下の通り。
~~~~~~~~~~~~~~~~~~
・構造体
・ポインタ/アドレス
・インターフェイス
・並列プログラミング(ゴールーチン/チャンネル)
etc...
~~~~~~~~~~~~~~~~~~

今回は、「並列プログラミング(Goルーチン/チャンネル)」を扱う。
なお、実行環境は、以下のサイトで気軽にできる。

https://play.golang.org/

目次

【1】Goルーチン (goroutine)
【2】チャンネル (channel)
【3】サンプル
 例1:Hello world
 例2:チャンネル

【1】Goルーチン (goroutine)

* 「go」を付けるだけで並列実行できる!

構文

go 関数名

【2】チャンネル (channel)

* channel により、Goルーチンとのデータのやりとりができる

【3】サンプル

例1:Hello world

package main

import (
  "fmt"
  "time"
)

func work() {
  time.Sleep(1 * time.Second)
  fmt.Println("Hello, Go routine!")
}

func main() {
  fmt.Println("Start")
  // 「go」を付けるだけで並列実行できる!
  go work()
  time.Sleep(3 * time.Second)
  fmt.Println("Done")
}

出力結果

Start
Hello, Go routine! << 1秒後
Done << 3秒後

例2:チャンネル

package main

import (
  "fmt"
)

func SayHello(name string, channel chan string) {
  // チャネルにデータを送信
  channel <- "Hello, " + name + "!"
}

func main() {
  // チャネル作成
  channel := make(chan string)
  // Goルーチンとして呼び出す
  go SayHello("Mike", channel)
  // 送られてきたデータを受信
  result := <-channel
  fmt.Println("Result : ", result)
}

出力結果

Result :  Hello, Mike!

関連記事

Golang ~ 環境設定編 ~
https://dk521123.hatenablog.com/entry/2020/04/03/000000
Golang ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/04/12/145237
Golang ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2020/04/05/000000
Golang ~ 基本編 / 関数 ~
https://dk521123.hatenablog.com/entry/2021/05/03/000000
Golang ~ 基本編 / ポインタ/アドレス ~
https://dk521123.hatenablog.com/entry/2021/05/02/000000
Golang ~ 基本編 / 構造体 ~
https://dk521123.hatenablog.com/entry/2021/05/01/000000