描述:
下面是Go编程语言第9-7章中的代码。
在调用任何其他函数之前,必须调用func New()来插入容器。
奇怪的是,作者在func New()中创建了一个阻塞通道来发送请求。
我认为这将使程序以一种连续的方式工作。
例如:如果同时有多个goroutine调用func (),那么服务器 goroutine的循环中会以串行方式处理请求吗?
有人能给我解释一下吗?谢谢!
/**
* create a memo and run the monitor goroutine of it.
* here is a question:
* since the request channel is blocking, does it mean that func Get is serial?
*/
func New(f Func) *Memo {
memo := &Memo{requests: make(chan request)}
go memo.server(f)
return memo
}
/**
* make a new request to query the data.
*/
func (memo *Memo) Get(key string) (interface{}, error) {
response := make(chan result)
memo.requests <- request{key, response}
res := <-response
return res.value, res.err
}
/**
* start the monitor goroutine.
* Notice that the cache is running here.
*/
func (memo *Memo) server(f Func) {
cache := make(map[string]*entry)
// handle each of the requests
for req := range memo.requests {
e := cache[req.key]
if e == nil {
e = &entry{ready: make(chan struct{})}
cache[req.key] = e
go e.call(f, req.key)
}
go e.deliver(req.response)
}
}发布于 2020-04-11 16:10:26
New函数在goroutine中启动server,server从requests通道读取请求。由于requests没有缓冲,因此在任何时候只有一个goroutine可以给它写信。但是,请注意服务器的实现:它读取一个请求,并启动一个新的goroutine来处理该请求,然后立即返回到从中侦听。因此,请求处理goroutine是一个接一个创建的,但是每个goroutine同时运行。
当您调用Get时,它会等待server方法来处理请求,但是一旦请求处理程序goroutine被创建,它就可以为其他Get请求服务。每个Get呼叫将等待一个响应到达一个不同的通道,由另一个goroutine编写。
因此,简单地说:不,可以从多个goroutines调用Get,并且每个调用都将创建一个单独的goroutine来处理该请求。
https://stackoverflow.com/questions/61159453
复制相似问题