Go 동시성
Go context: Cancellation and Timeouts
Stop work that takes too long or is no longer needed with context.WithTimeout and WithCancel.
배울 내용
- context.WithTimeout
- ctx.Done()
- context.WithCancel
Timeout of 50 ms
5 ms of worknil, finished in time500 ms of workcontext deadline exceededafter stop()context canceledA cancellation signal passed down
A context carries a cancellation signal through your program. Functions that may take a long time accept a context and stop when it is cancelled or its deadline passes.
WithTimeout creates a context that is cancelled after 50 milliseconds. slowOperation waits for either its work or ctx.Done(), whichever comes first, and returns ctx.Err() when the context wins. WithCancel returns a function that cancels the context by hand.
핵심 포인트
- A context is cancelled by a deadline or by hand.
ctx.Done()is a channel that closes on cancel.ctx.Err()says why.
실행 가능한 Go 예제
Go
main.go
package main
import (
"context"
"fmt"
"time"
)
func slowOperation(ctx context.Context, duration time.Duration) error {
select {
case <-time.After(duration):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
fmt.Println("quick:", slowOperation(ctx, 5*time.Millisecond))
fmt.Println("slow:", slowOperation(ctx, 500*time.Millisecond))
manual, stop := context.WithCancel(context.Background())
stop()
fmt.Println("cancelled:", slowOperation(manual, time.Second))
}
quick: <nil>
slow: context deadline exceeded
cancelled: context canceled연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지