mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-12-20 12:44:20 +08:00
ch9: fix code format
This commit is contained in:
@@ -19,8 +19,8 @@ func httpGetBody(url string) (interface{}, error) {
|
||||
|
||||
下面是我們要設計的cache的第一個“草稿”:
|
||||
|
||||
<u><i>gopl.io/ch9/memo1</i></u>
|
||||
```go
|
||||
gopl.io/ch9/memo1
|
||||
// Package memo provides a concurrency-unsafe
|
||||
// memoization of a function of type Func.
|
||||
package memo
|
||||
@@ -153,8 +153,8 @@ memo.go的32行出現了兩次,説明有兩個goroutine在沒有同步榦預
|
||||
|
||||
最簡單的使cache併發安全的方式是使用基於監控的同步。隻要給Memo加上一個mutex,在Get的一開始獲取互斥鎖,return的時候釋放鎖,就可以讓cache的操作發生在臨界區內了:
|
||||
|
||||
<u><i>gopl.io/ch9/memo2</i></u>
|
||||
```go
|
||||
gopl.io/ch9/memo2
|
||||
type Memo struct {
|
||||
f Func
|
||||
mu sync.Mutex // guards cache
|
||||
@@ -181,8 +181,8 @@ func (memo *Memo) Get(key string) (value interface{}, err error) {
|
||||
|
||||
下一個Get的實現,調用Get的goroutine會兩次獲取鎖:査找階段獲取一次,如果査找沒有返迴任何內容,那麽進入更新階段會再次獲取。在這兩次獲取鎖的中間階段,其它goroutine可以隨意使用cache。
|
||||
|
||||
<u><i>gopl.io/ch9/memo3</i></u>
|
||||
```go
|
||||
gopl.io/ch9/memo3
|
||||
func (memo *Memo) Get(key string) (value interface{}, err error) {
|
||||
memo.mu.Lock()
|
||||
res, ok := memo.cache[key]
|
||||
@@ -204,8 +204,8 @@ func (memo *Memo) Get(key string) (value interface{}, err error) {
|
||||
|
||||
理想情況下是應該避免掉多餘的工作的。而這種“避免”工作一般被稱爲duplicate suppression(重複抑製/避免)。下面版本的Memo每一個map元素都是指向一個條目的指針。每一個條目包含對函數f調用結果的內容緩存。與之前不同的是這次entry還包含了一個叫ready的channel。在條目的結果被設置之後,這個channel就會被關閉,以向其它goroutine廣播(§8.9)去讀取該條目內的結果是安全的了。
|
||||
|
||||
<u><i>gopl.io/ch9/memo4</i></u>
|
||||
```go
|
||||
gopl.io/ch9/memo4
|
||||
type entry struct {
|
||||
res result
|
||||
ready chan struct{} // closed when res is ready
|
||||
@@ -275,8 +275,8 @@ type entry struct {
|
||||
|
||||
然而Memo類型現在包含了一個叫做requests的channel,Get的調用方用這個channel來和monitor goroutine來通信。requests channel中的元素類型是request。Get的調用方會把這個結構中的兩組key都填充好,實際上用這兩個變量來對函數進行緩存的。另一個叫response的channel會被拿來發送響應結果。這個channel隻會傳迴一個單獨的值。
|
||||
|
||||
<u><i>gopl.io/ch9/memo5</i></u>
|
||||
```go
|
||||
gopl.io/ch9/memo5
|
||||
// A request is a message requesting that the Func be applied to key.
|
||||
type request struct {
|
||||
key string
|
||||
|
||||
Reference in New Issue
Block a user