如何根据文件描述符的数量限制 go 例程

我有一个对 HTTP 服务器执行查询的程序,每个请求都有一个 goroutine。我很快发现这对于 MacOS 来说太多了,因为文件描述符限制为 250。

我想知道是否可以限制 goroutine 的数量,或者在有可用的 goroutine 之前阻塞,而不是失败。

也许是一个有 250 个 goroutines 的工作池,并将其余的请求排队?

你怎么认为


芜湖不芜
浏览 78回答 1
1回答

元芳怎么了

package mainimport "fmt"const ROUTINE_LIMIT = 250func main() {&nbsp; &nbsp; channelCounter := make(chan bool, ROUTINE_LIMIT)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; //will add till 250 after that it will block&nbsp; &nbsp; &nbsp; &nbsp; case channelCounter <- true:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("added channel")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; go startRoutine(channelCounter)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func startRoutine(channelCounter chan bool) {&nbsp; &nbsp; /*&nbsp; &nbsp; &nbsp; &nbsp; do your stuff&nbsp; &nbsp; */&nbsp; &nbsp; //free the channel&nbsp; &nbsp; <-channelCounter}您可以使用通道限制您的 goruotine 计数。一个用于记录运行的 goroutine 数量的通道。一旦工作完成,您可以读取通道值以减少计数。上面的程序就像一个粗略的示例代码..(我认为它涵盖了一般想法)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go