How to use context cancellation in Goroutine?

王林
Release: 2024-06-06 10:29:43
Original
506 people have browsed it

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.

如何在 Goroutine 中使用上下文取消功能?

#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:

  • User cancels operation
  • Timeout task
  • Error handling when resource contention

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)
}
Copy after login

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.
  • The Goroutine will run an infinite loop, exiting when the ctx.Done() channel receives a signal.
  • The main process will exit after 10 seconds, and the Goroutine will be canceled at this time.

Practical Case

In real applications, context cancellation can be used for the following tasks:

  • Web Server: Cancel the HTTP handler when the user cancels the request.
  • Database connection: Cancel the database query when the database connection is no longer needed.
  • File I/O: Cancel the I/O operation when the file transfer needs to be cancelled.

Notes

Please pay attention to the following notes:

  • Use context.Done() Channel to listen for cancellation events.
  • You should use defer cancel() in Goroutine to cancel the context when the function returns.
  • Use the 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!