Go 동시성
Go Worker Pool
Share a queue of jobs between a fixed number of goroutines to limit how much runs at once.
배울 내용
- A jobs channel
- Several workers
- Closing results safely
6 jobs, 3 workers
- 1
jobs1 2 3 4 5 6 - 2
3 workersn * n - 3
results1 4 9 16 25 36
A fixed team of workers
A worker pool starts a fixed number of goroutines that all read jobs from one channel. It limits how much work runs at the same time, which protects memory, files and network connections.
Three workers read from jobs until it is closed and send each answer to results. A separate goroutine closes results after every worker has finished, which ends the final range loop. Each result carries its job number, so the order in which workers finish does not matter.
핵심 포인트
- All workers read from one jobs channel.
close(jobs)tells them to stop.- Results are closed after every worker is done.
실행 가능한 Go 예제
Go
main.go
package main
import (
"fmt"
"sync"
)
func worker(jobs <-chan int, results chan<- [2]int, wg *sync.WaitGroup) {
defer wg.Done()
for n := range jobs {
results <- [2]int{n, n * n}
}
}
func main() {
jobs := make(chan int)
results := make(chan [2]int)
var wg sync.WaitGroup
for w := 0; w < 3; w++ {
wg.Add(1)
go worker(jobs, results, &wg)
}
go func() {
for n := 1; n <= 6; n++ {
jobs <- n
}
close(jobs)
}()
go func() {
wg.Wait()
close(results)
}()
squares := make([]int, 7)
for result := range results {
squares[result[0]] = result[1]
}
fmt.Println(squares[1:])
}
[1 4 9 16 25 36]연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지