Home >Backend Development >Golang >How to Gracefully Kill Multiple Goroutines Simultaneously in Go?

How to Gracefully Kill Multiple Goroutines Simultaneously in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 00:48:11690browse

How to Gracefully Kill Multiple Goroutines Simultaneously in Go?

How to Kill Multiple Goroutines at Once in Go

In Go, you may encounter scenarios where you need to terminate multiple goroutines simultaneously. This is especially useful when one goroutine's completion should trigger the termination of others.

Consider the following code snippet:

func main() {

  go func() {
    ...
    if err != nil {
      return
    }
  }()

  go func() {
    ...
    if err != nil {
      return
    }
  }()

}

In this case, you want to ensure that when one of the goroutines returns, the other should also exit. A common approach to achieve this is to use channels for signaling. However, this may lead to a write to closed channel panic.

A reliable solution to this problem is leveraging Go's context mechanism. Context allows you to establish communication between routines and signal when an operation is completed or canceled. Here's an example:

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()
}

In this example, we create a context that can be passed to goroutines to check for termination signals. When the third goroutine completes its operation, it calls cancel(), which sends a signal to both goroutines waiting for its completion. As a result, all goroutines terminate gracefully.

The above is the detailed content of How to Gracefully Kill Multiple Goroutines Simultaneously in Go?. For more information, please follow other related articles on the PHP Chinese website!

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