diff options
author | Kevin Burke <kev@inburke.com> | 2016-06-22 10:00:31 -0700 |
---|---|---|
committer | Brad Fitzpatrick <bradfitz@golang.org> | 2016-11-10 05:32:14 +0000 |
commit | 9e2c3f4c7e78b01d635e16287789913d02807569 (patch) | |
tree | 36c313f7f8574278f16c27110cceee5cb692d324 | |
parent | 73497c7656fa55ac33bac960ecee806b9b07ae5e (diff) | |
download | go-9e2c3f4c7e78b01d635e16287789913d02807569.tar.gz go-9e2c3f4c7e78b01d635e16287789913d02807569.zip |
sync: add example for Pool
It was a little tricky to figure out how to go from the documentation
to figuring out the best way to implement a Pool, so I thought I'd
try to provide a simple example. The implementation is mostly taken
from the fmt package.
I'm not happy with the verbosity of the calls to WriteString() etc,
but I wanted to provide a non-trivial example.
Change-Id: Id33a8b6cbf8eb278f71e1f78e20205b436578606
Reviewed-on: https://go-review.googlesource.com/24371
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
-rw-r--r-- | src/sync/example_pool_test.go | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/sync/example_pool_test.go b/src/sync/example_pool_test.go new file mode 100644 index 0000000000..8288d41e8c --- /dev/null +++ b/src/sync/example_pool_test.go @@ -0,0 +1,45 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sync_test + +import ( + "bytes" + "io" + "os" + "sync" + "time" +) + +var bufPool = sync.Pool{ + New: func() interface{} { + // The Pool's New function should generally only return pointer + // types, since a pointer can be put into the return interface + // value without an allocation: + return new(bytes.Buffer) + }, +} + +// timeNow is a fake version of time.Now for tests. +func timeNow() time.Time { + return time.Unix(1136214245, 0) +} + +func Log(w io.Writer, key, val string) { + b := bufPool.Get().(*bytes.Buffer) + b.Reset() + // Replace this with time.Now() in a real logger. + b.WriteString(timeNow().UTC().Format(time.RFC3339)) + b.WriteByte(' ') + b.WriteString(key) + b.WriteByte('=') + b.WriteString(val) + w.Write(b.Bytes()) + bufPool.Put(b) +} + +func ExamplePool() { + Log(os.Stdout, "path", "/search?q=flowers") + // Output: 2006-01-02T15:04:05Z path=/search?q=flowers +} |