Home > Backend Development > Golang > How to Gracefully Terminate Multiple Go Routines Using Context?

How to Gracefully Terminate Multiple Go Routines Using Context?

Susan Sarandon
Release: 2024-12-10 05:48:14
Original
128 people have browsed it

How to Gracefully Terminate Multiple Go Routines Using Context?

How to Synchronize Multiple Go Routines with Context

To synchronize multiple goroutines, allowing them to terminate when one of them returns, context provides an effective solution.

Explanation:

The sample code creates two goroutines. To synchronize them, a context.Context is initiated and provided to both goroutines. Each goroutine enters a select {} loop, listening for messages from the context.

When an error occurs or a specific condition is met:

  1. The main goroutine calls the cancel function associated with the context.
  2. This sends a "done" message to the context.
  3. All goroutines listening to the context receive this message and terminate.

Code Sample:

package main

import (
    "context"
    "sync"
)

func main() {

    ctx, cancel := context.WithCancel(context.Background())
    wg := sync.WaitGroup{}
    wg.Add(3)
    go func() {
        defer wg.Done()
        for {
            select {
            // msg from other goroutine finish
            case <-ctx.Done():
                // end
            }
        }
    }()

    go func() {
        defer wg.Done()
        for {
            select {
            // msg from other goroutine finish
            case <-ctx.Done():
                // end
            }
        }
    }()

    go func() {
        defer wg.Done()
        // your operation
        // call cancel when this goroutine ends
        cancel()
    }()
    wg.Wait()
}
Copy after login

Advantages of Using Context:

  • Centralized Control: Avoids the need for explicit synchronization mechanisms, keeping the code clean.
  • Error Handling: If an error occurs in one goroutine, it can notify other goroutines through the context.
  • Graceful Termination: Goroutines receive a signal to terminate as soon as possible, preventing potential memory leaks.

The above is the detailed content of How to Gracefully Terminate Multiple Go Routines Using Context?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template