Go 并发控制:如何限制 Goroutine 数量

在 Go 语言中,使用 Goroutine 可以轻松实现并发编程。然而,无限制地创建 Goroutine 可能会导致资源竞争和程序崩溃。为了避免这种情况,我们需要控制 Goroutine 的数量。

本文将介绍如何使用通道(channel)和 sync.WaitGroup 对象来有效地限制并发 Goroutine 的数量。

使用通道和 sync.WaitGroup 限制 Goroutine 数量

以下是一种常见的方法,用于限制 Goroutine 的数量:

  1. **创建缓冲通道控制并发量:**goconcurrency := 5 // 设置最大并发量ch := make(chan struct{}, concurrency)

上述代码创建了一个带缓冲的通道 ch,缓冲区大小为 concurrency。 这限制了同时执行的 Goroutine 数量。

  1. **使用 sync.WaitGroup 等待所有 Goroutine 完成:**govar wg sync.WaitGroup

sync.WaitGroup 用于等待一组 Goroutine 完成。在创建新的 Goroutine 之前,调用 wg.Add(1) 来增加等待的 Goroutine 数量。在 Goroutine 执行完成后,调用 wg.Done() 来标记 Goroutine 完成。

  1. **启动 Goroutine 并使用通道控制:**gofor i := 0; i < 10; i++ { wg.Add(1) go func() { ch <- struct{}{} // 占用一个并发位置 // 执行任务 <-ch // 释放一个并发位置 wg.Done() }()}

在每个 Goroutine 的开始和结束处,通过向通道发送和接收数据来控制并发量。

  1. **等待所有 Goroutine 完成:**gowg.Wait() // 等待所有 Goroutine 完成

调用 wg.Wait() 会阻塞当前 Goroutine,直到所有已启动的 Goroutine 完成。

总结

通过以上方法,可以限制同时执行的 Goroutine 数量,并通过 sync.WaitGroup 等待所有 Goroutine 完成。

**代码示例:**gopackage main

import ( 'fmt' 'sync' 'time')

func worker(id int, ch chan struct{}, wg *sync.WaitGroup) { defer wg.Done() ch <- struct{}{} // 占用一个并发位置 fmt.Printf('Worker %d starting ', id) time.Sleep(time.Second) fmt.Printf('Worker %d done ', id) <-ch // 释放一个并发位置}

func main() { concurrency := 3 ch := make(chan struct{}, concurrency) var wg sync.WaitGroup

for i := 1; i <= 5; i++ {		wg.Add(1)		go worker(i, ch, &wg)	}

wg.Wait()	fmt.Println('All workers finished.')}

这个例子展示了如何使用通道和 sync.WaitGroup 限制并发执行的 worker Goroutine 数量。

希望这篇文章能帮助你理解如何在 Go 中有效地控制并发 Goroutine 的数量。

Go 并发控制:如何限制 Goroutine 数量

原文地址: https://www.cveoy.top/t/topic/PT3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录