<<Go Programming Language>> 中的一个奇怪问题
A weird problem in <<Go Programming Language>>
描述:
这是Go Programming Language第9-7章的代码。
您必须先调用 func New() 来初始化容器,然后再调用任何其他函数。
奇怪的是作者在func New()中创建了一个阻塞通道来发送请求。
我认为这将使程序以串行方式工作。
例如:如果有多个goroutine同时调用func Get(),那么在[=的循环中是否会串行处理请求26=]服务器协程?
谁能给我解释一下?谢谢!
/**
* 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)
}
}
New
函数在goroutine中启动server
,server
从requests
通道读取请求。由于 requests
是无缓冲的,任何时候只有一个 goroutine 可以写入它。但是,请注意服务器的实现:它读取一个请求,并启动一个新的 goroutine 来处理该请求,并立即返回监听它。所以,请求处理gorotines是一个一个创建的,但是每个goroutine都是并发运行的。
当你调用 Get
时,它等待 server
方法来处理请求,但是一旦创建了请求处理程序 goroutine,它就可以服务其他 Get
请求.每个 Get
调用将等待响应到达另一个 goroutine 写入的不同通道。
所以简而言之:不,Get
可以从许多 goroutines 中调用,并且每次调用都会创建一个单独的 goroutine 来处理该请求。
描述:
这是Go Programming Language第9-7章的代码。
您必须先调用 func New() 来初始化容器,然后再调用任何其他函数。
奇怪的是作者在func New()中创建了一个阻塞通道来发送请求。
我认为这将使程序以串行方式工作。
例如:如果有多个goroutine同时调用func Get(),那么在[=的循环中是否会串行处理请求26=]服务器协程?
谁能给我解释一下?谢谢!
/**
* 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)
}
}
New
函数在goroutine中启动server
,server
从requests
通道读取请求。由于 requests
是无缓冲的,任何时候只有一个 goroutine 可以写入它。但是,请注意服务器的实现:它读取一个请求,并启动一个新的 goroutine 来处理该请求,并立即返回监听它。所以,请求处理gorotines是一个一个创建的,但是每个goroutine都是并发运行的。
当你调用 Get
时,它等待 server
方法来处理请求,但是一旦创建了请求处理程序 goroutine,它就可以服务其他 Get
请求.每个 Get
调用将等待响应到达另一个 goroutine 写入的不同通道。
所以简而言之:不,Get
可以从许多 goroutines 中调用,并且每次调用都会创建一个单独的 goroutine 来处理该请求。