Use the context cancellation function in Go to gracefully cancel an ongoing Goroutine: use the context package to create a context with timeout. Use defer to cancel the context when the function returns. Use the select statement in Goroutine to listen for cancellation events.
#How to use context cancellation function in Goroutine?
In Go, the context cancellation mechanism allows us to gracefully cancel ongoing Goroutine when certain conditions are met. This is useful in tasks that need to run in the background but can be canceled if necessary.
Usage scenarios
Context cancellation is particularly suitable for the following scenarios:
Implementation details
To use context cancellation, you need to use the context
package. As shown below:
package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() go func() { for { select { case <-ctx.Done(): fmt.Println("Context cancelled!") return default: fmt.Println("Working...") time.Sleep(1 * time.Second) } } }() time.Sleep(10 * time.Second) }
In this example:
context.WithTimeout()
creates a new context that will time out for 5 seconds. defer cancel()
Ensures that the context is canceled when the main function returns. ctx.Done()
channel receives a signal. Practical Case
In real applications, context cancellation can be used for the following tasks:
Notes
Please pay attention to the following notes:
context.Done()
Channel to listen for cancellation events. defer cancel()
in Goroutine to cancel the context when the function returns. select
statement to listen for cancellation events in Goroutine when needed. The above is the detailed content of How to use context cancellation in Goroutine?. For more information, please follow other related articles on the PHP Chinese website!