Sobes.tech
Middle+

What is used to finish another goroutine from one goroutine?

sobes.tech AI

Answer from AI

In Go, to terminate one goroutine from another, contexts (context.Context) or channels are usually used.

1. Context (context.Context):

  • A cancelable context (context.WithCancel) is created.
  • It is passed to the goroutine.
  • When the goroutine needs to be terminated, the cancel function is called.
  • The goroutine should periodically check the context's state and terminate properly.

Example:

ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("Goroutine finished")
            return
        default:
            // work
        }
    }
}(ctx)

// In another goroutine or after an event
cancel() // signal to finish

2. Channels:

  • A signal channel is created.
  • The goroutine listens to the channel and terminates upon receiving a signal.

Example:

done := make(chan struct{})
go func() {
    for {
        select {
        case <-done:
            fmt.Println("Goroutine finished")
            return
        default:
            // work
        }
    }
}()

// To terminate the goroutine
close(done)

Thus, contexts or channels are used to manage the lifecycle of goroutines, allowing safe and proper termination.

What is used to finish another goroutine from one… - sobes.tech