🐾 [golang] context.WithCancel() 사용법
WithCanel()
WithCancel(parent Context) (ctx Context, cancel CancelFunc)
context.WithCancel()
- 혼자 사용할 수 없다.
WithCancel()
는 parent context를 넣어줘야한다. 그래서Background()
가 필요하다.- 새로운 context와 CancelFunc가 나온다.
- 호출하면 바로 context가 종료 된다.
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
fmt.Println(ctx.Err()) //nil
cancel() // 호출하면 컨텍스트가 종료가 된다.
fmt.Println(ctx.Err()) //context canceled
종료 신호를 받는 법
- ctx.Err()
- context가 종료 되었으면 에러를 반환한다.
- 종료가 됐는지 안됐는지 알 수 있다.
- ctx.Done()
- context가 종료 되었으면 채널에 값이 보내진다.
- 채널 값을 받으면 종료 됐는지 안됐는지 알수있다.
예시
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
fmt.Println("종료 전")
cancel()
select {
case <-ctx.Done():
fmt.Println("종료 시그널")
return
}
참조
https://github.com/YooGenie/go-study/issues/60