Maison > développement back-end > Golang > le corps du texte

Pourquoi devriez-vous toujours différer l'annulation d'un contexte dans Go ?

Mary-Kate Olsen
Libérer: 2024-11-14 10:00:03
original
124 Les gens l'ont consulté

Why Should You Always Defer Canceling a Context in Go?

Failure to Cancel Context: Consequences and Resolution

In Go's concurrency landscape, a Context governs the lifetime and behavior of goroutines. It provides a means to propagate deadlines, cancellation signals, and other essential information. However, failing to properly cancel a Context can lead to undesired consequences.

Consider the following code snippet:

func Call(ctx context.Context, payload Payload) (Response, error) {
    req, err := http.NewRequest(...) // Some code that creates request from payload
    ctx, cancel = context.WithTimeout(ctx, time.Duration(3) * time.Second)
    defer cancel()
    return http.DefaultClient.Do(req)
}
Copier après la connexion

Here, a new Context is created with a timeout of 3 seconds. Without the defer cancel() statement, the function returns without explicitly cancelling the Context. This triggers a warning from go vet:

the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

Context Leak and Its Implications

So, what happens if the Context is not cancelled? This omission creates a "leak" in the system. The goroutine that was responsible for handling the Context's cancellation remains active indefinitely, even though it serves no purpose. This wasted resource can result in a significant memory overhead if it occurs frequently within the program.

Best Practice: Immediate Cancellation

To avoid Context leaks, it is considered best practice to immediately defer cancel() after creating a new Context with WithCancel() or WithTimeout(). This ensures that the cancellation logic is executed as soon as the function returns, regardless of any early returns or exceptions.

In summary, neglecting to cancel a Context can lead to memory leaks by leaving goroutines running indefinitely. To prevent this, always defer the cancellation function immediately following the creation of a new Context with WithCancel() or WithTimeout().

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal