卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79840本站已运行4416

Golang 函数的 Goroutine 调度与并发

在 golang 中,使用 goroutine 实现函数的并发涉及以下步骤:创建 goroutine:使用 go 关键字执行函数或函数调用,例如:go func() { // goroutine 中的代码 }()。调度策略:golang 使用合作式和抢占式调度策略,允许 goroutine 交替执行。并发函数:创建一个包含多个 goroutine 的函数,使其同时执行。结果汇总:使用通道来接收和汇总 goroutine 返回的结果。

Golang 函数的 Goroutine 调度与并发

Golang 函数的 Goroutine 调度与并发

在 Golang 中,Goroutine 是轻量级线程,允许在同一应用程序中执行并发任务。Goroutine 的调度由 runtime 管理,本文将探讨在函数中使用 Goroutine 执行并发任务的策略。

Goroutine 创建

立即学习“go语言免费学习笔记(深入)”;

使用 go 关键字可以创建 Goroutine,该关键字后跟一个函数字面量或函数调用。例如:

func main() {
    go func() {
        // goroutine 中执行的代码
    }()
}

调度策略

Golang 的 runtime 使用以下策略调度 Goroutine:

  • 合作式调度:Goroutine 协作让出执行权给其他 Goroutine,通过 yield 函数或在 I/O 操作期间让出执行权。
  • 抢占式调度:对于某些类型的操作(如系统调用),runtime 会强制抢占 Goroutine 的执行权,以确保系统的响应能力。

并发函数

要创建并发函数,可以在函数中创建多个 Goroutine 并让它们同时执行。例如:

func doSomethingInParallel(requests []Request) {
    resultCh := make(chan Result, len(requests))

    // 为每个请求创建一个 Goroutine
    for _, request := range requests {
        go func(req Request) {
            // 处理请求并向结果通道发送结果
            result := doSomething(req)
            resultCh <- result
        }(request)
    }

    // 接收并汇总结果
    results := []Result{}
    for i := 0; i < len(requests); i++ {
        results = append(results, <-resultCh)
    }
}

在这个例子中,doSomethingInParallel 函数创建了一个 Goroutine 池来同时处理请求。结果通过一个通道汇总,该通道将每个 Goroutine 产生的结果发送到主函数。

实战案例

以下是一个使用函数级别并发处理图像文件大小的实战案例:

func resizeImagesInParallel(imagePaths []string) {
    resizedPathsCh := make(chan string, len(imagePaths))

    // 为每个图像创建 Goroutine
    for _, imagePath := range imagePaths {
        go func(path string) {
            // 调整图像大小并将路径发送到结果通道
            resizedPath := resizeImage(path)
            resizedPathsCh <- resizedPath
        }(imagePath)
    }

    // 接收并打印已调整图像的大小路径
    for i := 0; i < len(imagePaths); i++ {
        fmt.Println("Resized:", <-resizedPathsCh)
    }
}

此函数在单独的 Goroutine 中异步调整图像大小,并打印已调整图像的路径。它提高了图像调整的效率,尤其是在图像数量较多或图像文件较大时。

卓越飞翔博客
上一篇: php函数与人工智能结合时的困难及突破口
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏