Go 동시성

Go Channels

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

  • 고급
  • 3분 분량
  • 실행 가능한 예제 1개
배울 내용
  • 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.

핵심 포인트

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

실행 가능한 Go 예제

Go
코드 실행 →
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)
}
이 예제의 실행 버튼 만들기 코드 실행 결과
received: step 1 done
received: step 2 done
received: step 3 done
2 1 2

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Select and Timeouts →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지