Go 동시성

Goroutines and sync.WaitGroup

Start lightweight threads with the go keyword and wait for all of them to finish.

  • 고급
  • 3분 분량
  • 실행 가능한 예제 1개
배울 내용
  • The go keyword
  • WaitGroup: Add, Done, Wait
  • Writing results safely
Five goroutines
  1. 1wg.Add(1)count one more
  2. 2go square(...)runs on its own
  3. 3wg.Done()finished
  4. 4wg.Wait()main continues

Work that runs at the same time

A goroutine is a function that runs at the same time as the rest of the program. Writing go before a call starts one. Goroutines are cheap, so a program can run thousands of them.

main does not wait for goroutines by itself, so a WaitGroup counts them: Add before starting, Done when one finishes and Wait to block until the count is zero. Each goroutine writes to its own position of results, so the output is always the same.

핵심 포인트

  1. go f() starts f in a new goroutine.
  2. main does not wait by itself.
  3. wg.Wait blocks until every Done is called.

실행 가능한 Go 예제

Go
코드 실행 →
main.go
package main

import (
	"fmt"
	"sync"
)

func square(id int, results []int, wg *sync.WaitGroup) {
	defer wg.Done()
	results[id] = id * id
}

func main() {
	var wg sync.WaitGroup
	results := make([]int, 5)

	for id := 0; id < 5; id++ {
		wg.Add(1)
		go square(id, results, &wg)
	}

	wg.Wait() // block until every goroutine calls Done
	fmt.Println(results)
}
이 예제의 실행 버튼 만들기 코드 실행 결과
[0 1 4 9 16]

연습

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

이 레슨을 마쳤나요?

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

다음: Channels →

챌린지로 연습하기

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

모든 챌린지