首页 > 后端开发 > Golang > 在利用 goroutine 处理 URL 列表时,如何限制并发 Go 例程的数量?

在利用 goroutine 处理 URL 列表时,如何限制并发 Go 例程的数量?

Mary-Kate Olsen
发布: 2024-10-31 11:31:02
原创
549 人浏览过

How can you limit the number of concurrent Go routines when processing a list of URLs while utilizing goroutines?

限制并发 Go 例程的数量

问题:
您打算处理 URL 列表同时使用 goroutine,但同时执行的 goroutine 数量是预先定义的。在这种情况下,尽管有 30 个 URL,但您希望同时将并行化限制为 10 个 goroutine。

解决方案:

解决此问题的关键在于修改您的代码的架构。不要为每个 URL 生成单独的 goroutine,而是生成有限数量的工作 goroutine 来使用来自共享通道的 URL。此通道的缓冲性质将调节并发性。

代码修改:

以下是包含此方法的代码的更新版本:

<code class="go">package main

import (
    "flag"
    "fmt"
    "os"
    "sync"
    "time"
)

func main() {
    parallel := flag.Int("parallel", 10, "max parallel requests allowed")
    flag.Parse()
    urls := flag.Args()

    // Create a buffered channel to buffer URLs
    urlsChan := make(chan string, *parallel)

    // Create a separate goroutine to feed URLs into the channel
    go func() {
        for _, u := range urls {
            urlsChan <- u
        }
        // Close the channel to indicate that there are no more URLs to process
        close(urlsChan)
    }()

    var wg sync.WaitGroup
    client := rest.Client{}

    results := make(chan string)

    // Start the specified number of worker goroutines
    for i := 0; i < *parallel; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            // Continuously retrieve URLs from the channel until it is closed
            for url := range urlsChan {
                worker(url, client, results)
            }
        }()
    }

    // Launch a separate goroutine to close the results channel when all workers are finished
    go func() {
        // Wait for all workers to finish processing URLs
        wg.Wait()
        // Close the results channel to signal that there are no more results
        close(results)
    }()

    // Read results from the channel until it is closed
    for res := range results {
        fmt.Println(res)
    }

    os.Exit(0)
}</code>
登录后复制

在此修改后的代码中:

  1. 创建一个缓冲通道 urlsChan 来保存要处理的 URL。缓冲区大小设置为 *parallel,有效限制了可以同时访问通道的 goroutine 数量。
  2. 一个单独的 goroutine 专门用于使用 URL 填充 urlsChan 通道。
  3. worker goroutine持续使用 urlsChan 通道中的 URL,直到关闭。
  4. 一旦所有工作人员完成其任务,就会使用一个单独的 Goroutine 来关闭结果通道。

通过利用这种修改后的架构,可以根据指定的并行度限制,有效调控并发执行的goroutine数量。

以上是在利用 goroutine 处理 URL 列表时,如何限制并发 Go 例程的数量?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板