ゴルーチン
goroutine (ゴルーチン)は、Goのランタイムに管理される軽量なスレッド。
go f(x, y, z)
と書くことで新しいgoroutineが実行される。
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
// hello
// world
// world
// hello
// hello
// world
// world
// hello
// hello
チャネル
チャネル( Channel )型は、チャネルオペレータの <-
を用いて値の送受信ができる通り道。
通常、片方が準備できるまで送受信はブロックされる。
ch <- v // v をチャネル ch へ送信する
v := <-ch // ch から受信した変数を v へ割り当てる
チャネルは使う前に以下のように生成する。
ch := make(chan int)
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
// -5 17 12
バッファ
make の2つ目の引数にバッファの長さを指定できる
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
fmt.Println(<-ch)
fmt.Println(<-ch)
}
// 1
// 2