From 8b52f93ca586eb77aac1e7919e55067c36d350ac Mon Sep 17 00:00:00 2001 From: Stephen McQuay Date: Mon, 31 Mar 2014 21:15:34 -0700 Subject: [PATCH] Don't automatically do concurrency for users http://talks.golang.org/2013/bestpractices.slide#25 --- id.go | 19 ++++++++++--------- id_test.go | 1 + 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/id.go b/id.go index ad22b6e..108af32 100644 --- a/id.go +++ b/id.go @@ -18,15 +18,16 @@ type IdGenerator struct { } func NewIdGenerator() *IdGenerator { - g := IdGenerator{} - g.id = make(chan int64) - go func() { - var i int64 - for i = 0; ; i++ { - g.id <- i - } - }() - return &g + return &IdGenerator{ + id: make(chan int64), + } +} + +func (idg *IdGenerator) Run() { + var i int64 + for i = 0; ; i++ { + idg.id <- i + } } func (id *IdGenerator) Hash() string { diff --git a/id_test.go b/id_test.go index cb900c1..5c7f893 100644 --- a/id_test.go +++ b/id_test.go @@ -8,6 +8,7 @@ func TestIDGenerator(t *testing.T) { cache := make(map[string]bool) var cur string gg := NewIdGenerator() + go gg.Run() for i := 0; i < 10000; i++ { cur = gg.Hash() if _, ok := cache[cur]; ok {