Junior — Middle
Kas on võimalik olukord, kus goroutine katkestatakse või see lõpetab iseenda?
sobes.tech AI
Vastus AI-lt
In Go, the execution of a goroutine can terminate on its own in several cases:
- The goroutine has finished its function. As soon as the function run inside the goroutine completes, the goroutine ends.
- Panic inside the goroutine. If a panic occurs inside the goroutine and is not recovered, it will terminate abruptly.
- Cancellation via context. If the goroutine listens for a cancellation signal through
context.Contextand receives it, it can terminate properly.
It is important to understand that goroutines are not forcibly interrupted from outside — you need to implement a stop mechanism yourself, for example, through channels or contexts.
Example of using context to cancel a goroutine:
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("Goroutine finished")
return
default:
// work
}
}
}(ctx)
// At some point, call cancel()
cancel()
This way, the goroutine either finishes on its own after completing its work, or upon receiving a cancellation signal if it is set up to do so.