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 리뷰를 받을 수 있습니다.

모든 챌린지