Concurrence en Go

Go Channels

Send values between goroutines with channels: unbuffered, buffered, close and range.

  • Avancé
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • Send and receive
  • close and range
  • Buffered channels
Producer to main
  1. 1out <- messageproducer goroutine
  2. 2chan stringstep 1, step 2, step 3
  3. 3range messagesmain

A pipe between goroutines

A channel is a pipe that carries values from one goroutine to another. Sending and receiving wait for each other, so channels also keep goroutines in step.

out <- value sends and <-channel receives. An unbuffered channel hands each message directly to the receiver. close tells the receiver that nothing more will come, which ends the range loop. A buffered channel holds up to its capacity without a receiver.

Points clés

  1. ch <- v sends and <-ch receives.
  2. close ends a range loop.
  3. A buffered channel holds values without a receiver.

Exemple Go exécutable

Go
Exécuter le code →
main.go
package main

import "fmt"

func produce(steps int, out chan<- string) {
	for step := 1; step <= steps; step++ {
		out <- fmt.Sprintf("step %d done", step)
	}
	close(out) // tells the receiver there is nothing more
}

func main() {
	messages := make(chan string)
	go produce(3, messages)

	for message := range messages {
		fmt.Println("received:", message)
	}

	buffered := make(chan int, 2)
	buffered <- 1
	buffered <- 2
	fmt.Println(len(buffered), <-buffered, <-buffered)
}
Obtenir un bouton Run pour cet exemple Résultat de l'exécution
received: step 1 done
received: step 2 done
received: step 3 done
2 1 2

S'entraîner

Ouvrez l'exemple dans le compilateur en ligne, modifiez une valeur ou ajoutez une ligne, et devinez la sortie avant de l'exécuter. Cassez ensuite le code exprès et lisez le message du compilateur.

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Suivante : Select and Timeouts →

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis