Go の並行処理

Go select and Timeouts

Wait on several channels at once, give up after a timeout, or check without waiting.

  • 上級
  • 約4分で読めます
  • 実行できるサンプル 1 件
学べること
  • select with several cases
  • time.After
  • default
select
case <-fastready after 10 ms
case <-slowready after 200 ms
case <-time.After(50ms)timeout

The first ready channel wins

select waits for the first of several channel operations that is ready. It is how a goroutine listens to more than one channel, adds a timeout, or checks a channel without waiting.

The first select receives from fast because it is ready first. In the second, time.After delivers a value after 50 milliseconds, before slow is ready, so the timeout case runs. A default case runs at once when no channel is ready.

重要なポイント

  1. select runs the first case that is ready.
  2. time.After adds a timeout.
  3. default runs when nothing is ready.

実行できる Go のサンプル

Go
コードを実行 →
main.go
package main

import (
	"fmt"
	"time"
)

func main() {
	fast := make(chan string)
	slow := make(chan string)

	go func() {
		time.Sleep(10 * time.Millisecond)
		fast <- "fast result"
	}()
	go func() {
		time.Sleep(200 * time.Millisecond)
		slow <- "slow result"
	}()

	select {
	case message := <-fast:
		fmt.Println(message)
	case message := <-slow:
		fmt.Println(message)
	}

	select {
	case message := <-slow:
		fmt.Println(message)
	case <-time.After(50 * time.Millisecond):
		fmt.Println("timed out waiting for slow")
	}

	ready := make(chan int)
	select {
	case value := <-ready:
		fmt.Println(value)
	default:
		fmt.Println("nothing ready, moving on")
	}
}
この例の実行ボタンを作成 実行結果
fast result
timed out waiting for slow
nothing ready, moving on

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ