0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ゴルーチン、チャネル【Go】

Last updated at Posted at 2025-01-18

ゴルーチン

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?