Sobes.tech
Junior — Middle

How does a goroutine know that it has been signaled to finish through the context?

sobes.tech AI

Answer from AI

A goroutine receives a completion signal through a context using a channel provided by the context.Context object. Typically, the Done() method is used, which returns a channel that closes when the context is canceled. The goroutine can listen to this channel in a loop or select statement and react to its closure, which indicates a signal for completion or cancellation of the operation.

Example:

ctx, cancel := context.WithCancel(context.Background())

go func() {
    select {
    case <-ctx.Done():
        // Context is canceled, finish work
        fmt.Println("Goroutine finished")
        return
    // other cases
    }
}()

// Later, call cancel() to signal completion
cancel()