GO · 고루틴/채널
취소 전파
컨텍스트 취소가 부모에서 자식으로 전파되는 패턴. 중첩된 고루틴 트리를 안전하게 종료합니다.
고루틴/채널중급contextcancelpropagationgoroutine
핵심 설명
컨텍스트 취소가 부모에서 자식으로 전파되는 패턴. 중첩된 고루틴 트리를 안전하게 종료합니다.
Go code
package main
import (
"context"
"fmt"
"time"
)
func parentTask(ctx context.Context) {
childCtx, cancel := context.WithCancel(ctx)
defer cancel()
go childTask(childCtx, "A")
go childTask(childCtx, "B")
select {
case <-ctx.Done():
fmt.Println("부모 취소됨 → 자식들도 자동 취소")
case <-time.After(5 * time.Second):
fmt.Println("부모 완료")
}
}
func childTask(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Printf("자식 %s 종료: %v\n", name, ctx.Err())
return
case <-time.After(500 * time.Millisecond):
fmt.Printf("자식 %s 작업 중...\n", name)
}
}
}
func main() {
ctx, cancel := context.WithTimeout(
context.Background(), 2*time.Second,
)
defer cancel()
parentTask(ctx)
time.Sleep(100 * time.Millisecond) // 정리 대기
}학습 팁
부모 context가 취소되면 모든 자식 context도 자동 취소됩니다. 별도의 종료 신호 채널이 필요 없습니다.
주의할 점
자식 context의 cancel을 호출하지 않으면 context가 GC되기 전까지 부모 context에 연결된 상태로 남아 메모리 누수가 발생합니다.
자주 묻는 질문
취소 전파란 무엇인가요?
컨텍스트 취소가 부모에서 자식으로 전파되는 패턴. 중첩된 고루틴 트리를 안전하게 종료합니다.
취소 전파 학습 시 주의할 점은 무엇인가요?
자식 context의 cancel 을 호출하지 않으면 context가 GC되기 전까지 부모 context에 연결된 상태로 남아 메모리 누수가 발생합니다.