我不太了解golang频道

这些天,Goroutines 和通道困扰着我。我正在查看https://github.com/adonovan/gopl.io/tree/master/ch9上的 memo5 代码。如果你看 memo5 的 memo.go,有func (e *entry) call(f Func, key string)和func (e *entry) deliver(response chan<- result)部分。


// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.

// License: https://creativecommons.org/licenses/by-nc-sa/4.0/


// See page 278.


// Package memo provides a concurrency-safe non-blocking memoization

// of a function.  Requests for different keys proceed in parallel.

// Concurrent requests for the same key block until the first completes.

// This implementation uses a monitor goroutine.

package memo


//!+Func


// Func is the type of the function to memoize.

type Func func(key string) (interface{}, error)


// A result is the result of calling a Func.

type result struct {

    value interface{}

    err   error

}


type entry struct {

    res   result

    ready chan struct{} // closed when res is ready

}


//!-Func


//!+get


// A request is a message requesting that the Func be applied to key.

type request struct {

    key      string

    response chan<- result // the client wants a single result

}


type Memo struct{ requests chan request }


// New returns a memoization of f.  Clients must subsequently call Close.

func New(f Func) *Memo {

    memo := &Memo{requests: make(chan request)}

    go memo.server(f)

    return memo

}


func (memo *Memo) Get(key string) (interface{}, error) {

    response := make(chan result)

    memo.requests <- request{key, response}

    res := <-response

    return res.value, res.err

}


我不明白如何在 close(e.ready)这里 <-e.ready同步。就算看完书,也看不懂。请告诉我机制是什么。


森栏
浏览 142回答 1
1回答

拉丁的传说

e.ready更多地被称为done&nbsp;通道。这是一种通过关闭done(&nbsp;e.readychan) 来告诉您的 ref 函数 dothing 已准备好的方法。<-e.ready将阻塞直到它的done(&nbsp;closed)。所以...阅读此代码意味着下一步。deliver等待红色信号。call获取 e.res&nbsp; (e.res.value 的数据,e.res.err = f(key)`)call通过关闭它来释放完成的通道 (&nbsp;close(e.ready))deliver可以通过块读取移动<-e.ready并将数据发送到response
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go