Home >Backend Development >Golang >Creation and management of goroutine in Golang functions

Creation and management of goroutine in Golang functions

王林
王林Original
2024-06-05 19:06:011144browse

In Go language, create goroutine using go keyword plus function call. When managing goroutine, use sync.WaitGroup for synchronization; use the context package to cancel goroutine. In actual combat, it can be used to process network requests, image processing and other tasks in parallel.

Golang 函数中 goroutine 的创建和管理

Creation and management of goroutine in Golang functions

Goroutine (coroutine) is a lightweight parallel execution unit in the Go language that can be executed in a single thread Run multiple tasks concurrently at the same time.

Create Goroutine

Creating a goroutine is very simple. You can use the go keyword followed by a function call:

func hello() {
    fmt.Println("Hello from goroutine")
}

func main() {
    go hello() // 创建一个执行 hello() 函数的 goroutine
}

Goroutine Management

Synchronization

When dealing with shared resources, goroutine needs to be synchronized. Use sync.WaitGroup to wait for a group of goroutines to complete:

var wg sync.WaitGroup

func hello(name string) {
    wg.Add(1)
    defer wg.Done()

    fmt.Println("Hello", name)
}

func main() {
    wg.Add(3)
    go hello("John")
    go hello("Mary")
    go hello("Bob")
    wg.Wait() // 等待所有 goroutine 完成
}

Cancel

You can use the context package to cancel the goroutine:

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

func heavyComputation(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("Computation cancelled")
            return
        default:
            // 执行计算
        }
    }
}

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

    go heavyComputation(ctx)
    time.Sleep(10 * time.Second) // 10 秒后取消计算
}

actual case

Parallel processing of network requests:

func main() {
    urls := []string{"https://example.com", "https://example.net", "https://example.org"}

    var wg sync.WaitGroup

    for _, url := range urls {
        wg.Add(1)
        go func(url string) {
            resp, err := http.Get(url)
            if err != nil {
                log.Fatal(err)
            }

            resp.Body.Close()
            wg.Done()
        }(url)
    }

    wg.Wait()
}

Parallel processing of image processing:

func main() {
    images := []string{"image1.jpg", "image2.jpg", "image3.jpg"}

    var wg sync.WaitGroup

    for _, image := range images {
        wg.Add(1)
        go func(image string) {
            img, err := image.Decode(image)
            if err != nil {
                log.Fatal(err)
            }

            // 处理图像

            wg.Done()
        }(image)
    }

    wg.Wait()
}

The above is the detailed content of Creation and management of goroutine in Golang functions. 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