亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我不太了解golang頻道

我不太了解golang頻道

Go
森欄 2022-11-08 15:42:44
這些天,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同步。就算看完書,也看不懂。請告訴我機制是什么。
查看完整描述

1 回答

?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

e.ready更多地被稱為done 通道。這是一種通過關閉donee.readychan) 來告訴您的 ref 函數 dothing 已準備好的方法。<-e.ready將阻塞直到它的doneclosed)。

所以...閱讀此代碼意味著下一步。

  1. deliver等待紅色信號。

  2. call獲取 e.res  (e.res.value 的數據,e.res.err = f(key)`)

  3. call通過關閉它來釋放完成的通道 ( close(e.ready))

  4. deliver可以通過塊讀取移動<-e.ready并將數據發送到response


查看完整回答
反對 回復 2022-11-08
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號