Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

initial commit

  • Loading branch information...
commit 9020593c80bdeebcf32c20626b748cf75f1518e0 0 parents
nf@wh3rd.net authored
Showing with 73 additions and 0 deletions.
  1. +11 −0 Makefile
  2. +17 −0 README
  3. +26 −0 uniq.go
  4. +19 −0 uniq_test.go
11 Makefile
@@ -0,0 +1,11 @@
+# Copyright 2009 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.
+
+include $(GOROOT)/src/Make.inc
+
+TARG=uniq
+GOFILES=\
+ uniq.go\
+
+include $(GOROOT)/src/Make.pkg
17 README
@@ -0,0 +1,17 @@
+
+Implementation and benchmarks of the two methods of generating unique numbers
+described in this blog post:
+ http://nf.id.au/concurrency-patterns-a-source-of-unique-numbe
+
+The output of 'gomake bench':
+
+uniq.BenchmarkMutex 10000000 173 ns/op
+uniq.BenchmarkChannel 10000000 224 ns/op
+
+The channel-based approach takes 1.29x the time of the mutex-based approach.
+
+Depending on the specific application, and your opinion on the aesthetics
+of the two approaches, this can be an acceptable tradeoff (it is, IMO).
+
+Andrew Gerrand <nf@wh3rd.net>
+
26 uniq.go
@@ -0,0 +1,26 @@
+package uniq
+
+import (
+ "sync"
+)
+
+var (
+ uniqLock sync.Mutex
+ uniqId int
+)
+
+func uniqFn() int {
+ uniqLock.Lock()
+ defer uniqLock.Unlock()
+ uniqId++
+ return uniqId
+}
+
+var uniq = make(chan int)
+
+func init() {
+ go func() {
+ for i := 1;; i++ { uniq <- i }
+ }()
+}
+
19 uniq_test.go
@@ -0,0 +1,19 @@
+package uniq
+
+import (
+ "testing"
+)
+
+func BenchmarkMutex(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ uniqFn()
+ }
+}
+
+func BenchmarkChannel(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ <-uniq
+ }
+}
+
+func TestFoo(t *testing.T) { }
Please sign in to comment.
Something went wrong with that request. Please try again.