【问题标题】:How to limit go routines based on number of file descriptors如何根据文件描述符的数量限制 Go 例程
【发布时间】:2020-02-12 16:50:49
【问题描述】:
我有一个对 HTTP 服务器执行查询的程序,每个请求都有一个 goroutine。
我很快发现这对于 MacOS 来说太多了,因为文件描述符限制为 250。
我想知道是否可以限制 goroutine 的数量,或者在有可用的 goroutine 之前阻塞,而不是失败。
也许是一个包含 250 个 goroutine 的工作池,并将其余请求排队?
你有什么想法
【问题讨论】:
标签:
go
file-descriptor
goroutine
【解决方案1】:
package main
import "fmt"
const ROUTINE_LIMIT = 250
func main() {
channelCounter := make(chan bool, ROUTINE_LIMIT)
for {
select {
//will add till 250 after that it will block
case channelCounter <- true:
fmt.Println("added channel")
go startRoutine(channelCounter)
}
}
}
func startRoutine(channelCounter chan bool) {
/*
do your stuff
*/
//free the channel
<-channelCounter
}
您可以使用频道限制您的 goruotine 计数。
一个通道,用于计算运行的 goroutine 的数量..
一旦工作完成,您可以读取通道值以减少计数。
上面的程序就像一个粗略的示例代码..(我认为它涵盖了总体思路)