限制并发 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>
在此修改后的代码中:
通过利用这种修改后的架构,可以根据指定的并行度限制,有效调控并发执行的goroutine数量。
以上是在利用 goroutine 处理 URL 列表时,如何限制并发 Go 例程的数量?的详细内容。更多信息请关注PHP中文网其他相关文章!