Golang - context를 통한 고루틴 제어

00_8_3·2023년 2월 20일
0

Go

목록 보기
4/10

Go 언어에서 context 패키지는 고루틴 간에 값을 전달하고
요청 취소 등을 관리하는데 사용됩니다.

이를 통해 작업을 취소하거나 여러 고루틴 간의 값을 동시에 관리할 수 있습니다.

아래는 간단한 예시입니다.

context.WithTimeout

WithTimeout은 context를 생성하고, 해당 context가 지정된 시간 내에 취소될 때 실행할 취소 함수를 제공합니다.
이를 통해 다른 고루틴이 해당 context를 사용할 때
일정 시간 내에 작업이 완료되지 않으면 즉시 알 수 있습니다.

package main

import (
	"context"
	"fmt"
	"time"
)

func worker(ctx context.Context) {
    for {
        select {
        default:
            fmt.Println("working...")
            time.Sleep(500 * time.Millisecond)
        case <-ctx.Done():
            fmt.Println("context canceled")
            return
        }
    }
}

func main() {
    // 새로운 context 생성
    ctx := context.Background()

    // 1초 대기 시간을 가진 context 생성
    timeoutCtx, cancelFunc := context.WithTimeout(ctx, 1*time.Second)
    defer cancelFunc()

    // 고루틴 실행
    go worker(timeoutCtx)

    // 대기
    time.Sleep(2 * time.Second)
}

출력결과

working...
working...
context canceled

cancelFunc이 실행되기 전에 (메인 스레드 대기 시간 끝나기 전)
context의 대기시간이 지나게 되면 ctx.Done을 통해 알 수 있음.

만약 대기시간이 지나기 전에 cancelFunc이 실행되면
Done이 실행 안됨.

WithTimeout 함수 안의 time.Second를 3으로 하면 Done이 실행 안됨.

Context.WithCancel

WithCancel은 context를 생성하고,
해당 context가 취소될 때 실행할 취소 함수를 제공합니다.
이를 통해 다른 고루틴이 해당 context를 사용할 때
context가 취소될 때 즉시 알 수 있습니다.

아래는 WithCancel을 사용한 예시입니다.

package main

import (
    "context"
    "fmt"
    "time"
)

func worker(ctx context.Context) {
    for {
        select {
        default:
            fmt.Println("working...")
            time.Sleep(500 * time.Millisecond)
        case <-ctx.Done():
            fmt.Println("context canceled")
            return
        }
    }
}

func main() {
    // 새로운 context 생성
    ctx := context.Background()

    // context 취소 함수 생성
    cancelCtx, cancelFunc := context.WithCancel(ctx)

    // 고루틴 실행
    go worker(cancelCtx)

    // 3초 대기 후 context 취소 함수 호출
    time.Sleep(3 * time.Second)
    cancelFunc()

}

출력 결과

working...
working...
working...
working...
working...
working...
context cancled

메인에서 취소 함수를 호출 할 때 까지
고루틴에서 working을 출력하다가
3초 sleep 이후 실행이 되면
ctx.Done을 통해 context가 만료된 것을 알게 된다.

context.WithDeadline

WithDeadline 함수의 경우 WithTimeout과 마찬가지로
둘 다 지정된 시간 내에 작업이 완료되지 않으면 context가 취소되도록 하는 기능을 제공합니다.

그러나 두 함수의 차이점은
WithTimeout은 상대적인 시간 간격을 사용하여 취소 시간을 설정하는 반면,
WithDeadline은 절대적인 시간을 사용하여 취소 시간을 설정합니다.

예를 들어

WithTimeout는 1초라는 상대적인 시간을 통해 실행된 순간 부터
1초 후를 카운트 한다면

WithDeadline은 특정 시간대를 설정하여

2023-02-20 16:17:29.955728555 +0900 KST m=+3.000035940와 같은
Time 객체

그 시간에 작업이 완료됨을 말합니다.

  • 코드는 생략.

0개의 댓글