Commit 61978aa5 authored by Rob Pike's avatar Rob Pike

effective go: remove non-blocking ops in leaky bucket example

R=rsc
CC=golang-dev
https://golang.org/cl/4029048
parent 161f109c
...@@ -2526,39 +2526,49 @@ var serverChan = make(chan *Buffer) ...@@ -2526,39 +2526,49 @@ var serverChan = make(chan *Buffer)
func client() { func client() {
for { for {
b, ok := <-freeList // grab a buffer if available var b *Buffer
if !ok { // if not, allocate a new one // Grab a buffer if available; allocate if not.
select {
case b = <-freeList:
// Got one; nothing more to do.
default:
// None free, so allocate a new one.
b = new(Buffer) b = new(Buffer)
} }
load(b) // read next message from the net load(b) // Read next message from the net.
serverChan <- b // send to server serverChan <- b // Send to server.
} }
} }
</pre> </pre>
<p> <p>
The server loop receives messages from the client, processes them, The server loop receives each message from the client, processes it,
and returns the buffer to the free list. and returns the buffer to the free list.
</p> </p>
<pre> <pre>
func server() { func server() {
for { for {
b := &lt;-serverChan // wait for work b := &lt;-serverChan // Wait for work.
process(b) process(b)
_ = freeList &lt;- b // reuse buffer if room // Reuse buffer if there's room.
select {
case freeList &lt;- b:
// Buffer on free list; nothing more to do.
default:
// Free list full, just carry on.
}
} }
} }
</pre> </pre>
<p> <p>
The client's non-blocking receive from <code>freeList</code> obtains a The client attempts to retrieve a buffer from <code>freeList</code>;
buffer if one is available; otherwise the client allocates if none is available, it allocates a fresh one.
a fresh one. The server's send to <code>freeList</code> puts <code>b</code> back
The server's non-blocking send on freeList puts <code>b</code> back
on the free list unless the list is full, in which case the on the free list unless the list is full, in which case the
buffer is dropped on the floor to be reclaimed by buffer is dropped on the floor to be reclaimed by
the garbage collector. the garbage collector.
(The assignment of the send operation to the blank identifier (The <code>default</code> clauses in the <code>select</code>
makes it non-blocking but ignores whether statements execute when no other case is ready,
the operation succeeded.) meaning that the <code>selects</code> never block.)
This implementation builds a leaky bucket free list This implementation builds a leaky bucket free list
in just a few lines, relying on the buffered channel and in just a few lines, relying on the buffered channel and
the garbage collector for bookkeeping. the garbage collector for bookkeeping.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment