首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 ><<Go编程Language>>中一个奇怪的问题

<<Go编程Language>>中一个奇怪的问题
EN

Stack Overflow用户
提问于 2020-04-11 15:41:16
回答 1查看 48关注 0票数 1

描述:

下面是Go编程语言第9-7章中的代码。

在调用任何其他函数之前,必须调用func New()来插入容器。

奇怪的是,作者在func New()中创建了一个阻塞通道来发送请求。

我认为这将使程序以一种连续的方式工作。

例如:如果同时有多个goroutine调用func (),那么服务器 goroutine的循环中会以串行方式处理请求吗?

有人能给我解释一下吗?谢谢!

代码语言:javascript
复制
/**
 * 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)
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-11 16:10:26

New函数在goroutine中启动serverserverrequests通道读取请求。由于requests没有缓冲,因此在任何时候只有一个goroutine可以给它写信。但是,请注意服务器的实现:它读取一个请求,并启动一个新的goroutine来处理该请求,然后立即返回到从中侦听。因此,请求处理goroutine是一个接一个创建的,但是每个goroutine同时运行。

当您调用Get时,它会等待server方法来处理请求,但是一旦请求处理程序goroutine被创建,它就可以为其他Get请求服务。每个Get呼叫将等待一个响应到达一个不同的通道,由另一个goroutine编写。

因此,简单地说:不,可以从多个goroutines调用Get,并且每个调用都将创建一个单独的goroutine来处理该请求。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61159453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档