go之《 Go编程语言》中的一个奇怪问题

Demo 阅读:167 2025-06-02 22:19:02 评论:0

说明:
这是 Go编程语言的第9-7章中的代码。

您必须先调用 func New()来初始化容器,然后再调用其他函数。

作者在 func New()中创建了一个阻止 channel 来发送请求,这很奇怪。

我认为这将使程序以串行方式运行。

例如:如果有多个goroutine同时调用 func Get(),是否在服务器 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) 
    } 
} 
 

请您参考如下方法:

New函数在goroutine中启动server,并且serverrequests channel 读取请求。由于requests是未缓冲的,因此任何时候只能有一个goroutine可以对其进行写入。但是,请注意服务器的实现:它读取一个请求,并启动一个新的goroutine来处理该请求,然后立即返回监听该请求的过程。因此,请求处理gorotine是一个一个地创建的,但是每个goroutine并发运行。

调用Get时,它将等待server方法处理该请求,但是,一旦创建了请求处理程序goroutine,它便可以处理其他Get请求。每个Get调用将等待响应到达另一个goroutine编写的不同 channel 。

简而言之:不,可以从许多goroutine中调用Get,并且每次调用都会创建一个单独的goroutine来处理该请求。


标签:编程语言
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号