返回顶部
首页 > 资讯 > 精选 >Golang 函数中 goroutine 的创建和管理
  • 460
分享到

Golang 函数中 goroutine 的创建和管理

函数golanggo语言 2024-05-23 16:05:11 460人浏览 泡泡鱼
摘要

Go语言中,创建goroutine使用go关键字加函数调用。管理goroutine时,使用sync.waitgroup进行同步;使用context包可取消goroutine。实战中可用于

Go语言中,创建goroutine使用go关键字加函数调用。管理goroutine时,使用sync.waitgroup进行同步;使用context包可取消goroutine。实战中可用于并行处理网络请求、图片处理等任务。

golang 函数中 goroutine 的创建和管理

Goroutine(协程)是 Go 语言中的轻量级并行执行单元,可以在单个线程中同时并发运行多个任务。

创建 Goroutine

创建一个 goroutine 非常简单,可以使用 go 关键字后跟一个函数调用即可:

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

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

Goroutine 管理

同步

在处理共享资源时,需要对 goroutine 进行同步。使用 sync.WaitGroup 可以等待一组 goroutine 完成:

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 完成
}

取消

可以使用 context 包取消 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 秒后取消计算
}

实战案例

并行处理网络请求:

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

并行处理图片处理:

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

以上就是Golang 函数中 goroutine 的创建和管理的详细内容,更多请关注编程网其它相关文章!

--结束END--

本文标题: Golang 函数中 goroutine 的创建和管理

本文链接: https://www.lsjlt.com/news/618916.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作