Files
the-way-to-go_ZH_CN/eBook/14.11.md
2022-05-17 16:26:06 +08:00

47 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 14.11 限制同时处理的请求数
使用带缓冲区的通道很容易实现这一点(参见 [14.2.5](14.2.md#1425-%E5%90%8C%E6%AD%A5%E9%80%9A%E9%81%93-%E4%BD%BF%E7%94%A8%E5%B8%A6%E7%BC%93%E5%86%B2%E7%9A%84%E9%80%9A%E9%81%93)),其缓冲区容量就是同时处理请求的最大数量。程序 [max_tasks.go](examples/chapter_14/max_tasks.go) 虽然没有做什么有用的事但是却包含了这个技巧:超过 `MAXREQS` 的请求将不会被同时处理,因为当信号通道表示缓冲区已满时 `handle()` 函数会阻塞且不再处理其他请求,直到某个请求从 `sem` 中被移除。`sem` 就像一个信号量,这一专业术语用于在程序中表示特定条件的标志变量。
示例14.16-[max_tasks.go](examples/chapter_14/max_tasks.go)
```go
package main
const MAXREQS = 50
var sem = make(chan int, MAXREQS)
type Request struct {
a, b int
replyc chan int
}
func process(r *Request) {
// do something
}
func handle(r *Request) {
sem <- 1 // doesn't matter what we put in it
process(r)
<-sem // one empty place in the buffer: the next request can start
}
func server(service chan *Request) {
for {
request := <-service
go handle(request)
}
}
func main() {
service := make(chan *Request)
go server(service)
}
```
通过这种方式,应用程序可以通过使用缓冲通道(通道被用作信号量)使协程同步其对该资源的使用,从而充分利用有限的资源(如内存)。
## 链接
- [目录](directory.md)
- 上一节:[复用](14.10.md)
- 下一节:[链式协程](14.12.md)