Home >Backend Development >Golang >How to manage Goroutine lifecycle in Go?

How to manage Goroutine lifecycle in Go?

PHPz
PHPzOriginal
2024-06-04 09:34:57366browse

The core methods of managing the Goroutine life cycle in Go are as follows: Use context.Context: Control the Goroutine life cycle through cancellation signals and deadlines. Use sync.WaitGroup: Wait for the Goroutine to complete its task so that the main Goroutine can continue execution. Use channels: coordinate multiple Goroutines through signal communication, and wait for subsequent processing after all Goroutines are completed.

如何在 Go 中管理 Goroutine 的生命周期?

Manage the life cycle of Goroutine in Go

Goroutine is a lightweight thread in Go that supports concurrency. Their management is crucial to prevent resource leaks and program crashes. This article will explore various methods of managing the Goroutine life cycle, including:

1. Using context.Context

context.Context Provides a mechanism to propagate cancellation and deadline signals within Goroutine. To use it to manage the Goroutine life cycle, you can use the following steps:

package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    go func() {
        // Goroutine 的代码
    }()

    // 等待 Goroutine 完成,或超时。
    select {
    case <-ctx.Done():
        fmt.Println("Goroutine 已取消或超时。")
    }
}

2. Use sync.WaitGroup

sync .WaitGroup Allows Goroutines to wait for each other until they complete their respective tasks. Use it to manage the life cycle of Goroutine. You can wait in the main Goroutine for all child Goroutines to complete.

package main

import (
    "fmt"
    "runtime"
    "sync"
)

func main() {
    wg := sync.WaitGroup{}

    // 创建 5 个子 Goroutine
    for i := 0; i < 5; i++ {
        wg.Add(1) // 递增WaitGroup计数,表明正在等待另一个Goroutine完成

        go func(i int) {
            fmt.Printf("Goroutine %d 结束。\n", i)
            wg.Done() // 递减WaitGroup计数,表明Goroutine已完成
        }(i)
    }

    // 等待所有子 Goroutine 完成
    wg.Wait()

    fmt.Println("所有子 Goroutine 都已完成。")
}

3. Using channels

Channels can communicate between Goroutines and can also be used to manage their life cycles. A master goroutine can wait for all child goroutines to complete by sending a signal to a channel that marks the goroutine as completed.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    signals := make(chan struct{})

    // 创建 5 个子 Goroutine
    for i := 0; i < 5; i++ {
        wg.Add(1)

        go func(i int) {
            defer wg.Done() // Goroutine退出时递减WaitGroup计数

            // 等待其他Goroutine完成
            <-signals
            fmt.Printf("Goroutine %d 已完成。\n", i)
        }(i)
    }

    // 等待所有子 Goroutine完成
    wg.Wait()

    // 发送信号标记所有子Goroutine都已完成
    close(signals)

    fmt.Println("所有子 Goroutine 都已完成。")
}

The above is the detailed content of How to manage Goroutine lifecycle 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