Concorrência em Go

Go select and Timeouts

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

  • Avançado
  • 4 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • 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.

Pontos-chave

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

Exemplo executável de Go

Go
Executar código →
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")
	}
}
Gerar um botão Run para este exemplo Resultado da execução
fast result
timed out waiting for slow
nothing ready, moving on

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios