From 7f8715f392e082bfe8ff6051b95755a86e37b324 Mon Sep 17 00:00:00 2001 From: zhangbb <854641898@qq.com> Date: Sun, 12 Dec 2021 20:11:45 +0800 Subject: [PATCH] =?UTF-8?q?perf:=E6=8F=90=E4=BE=9B=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=9B=B4=E8=83=BD=E4=BD=93=E7=8E=B0Do()=E4=BD=9C=E7=94=A8?= =?UTF-8?q?=E7=9A=84test=20case?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../singleflight/singleflight_test.go | 29 +++++++++++++++++++ .../singleflight/singleflight_test.go | 29 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/gee-cache/day6-single-flight/geecache/singleflight/singleflight_test.go b/gee-cache/day6-single-flight/geecache/singleflight/singleflight_test.go index 450951a..44c865d 100644 --- a/gee-cache/day6-single-flight/geecache/singleflight/singleflight_test.go +++ b/gee-cache/day6-single-flight/geecache/singleflight/singleflight_test.go @@ -1,11 +1,14 @@ package singleflight import ( + "sync" "testing" + "time" ) func TestDo(t *testing.T) { var g Group + v, err := g.Do("key", func() (interface{}, error) { return "bar", nil }) @@ -14,3 +17,29 @@ func TestDo(t *testing.T) { t.Errorf("Do v = %v, error = %v", v, err) } } + +func TestGoDo(t *testing.T) { + var g Group + wg := sync.WaitGroup{} + + times := 10 + wg.Add(times) + for i := 0; i < times; i++ { + go func() interface{} { + v, err := g.Do("key", func() (interface{}, error) { + time.Sleep(time.Millisecond * 50) + return "bar", nil + }) + + wg.Done() + + if v != "bar" || err != nil { + t.Errorf("Do v = %v, error = %v", v, err) + } + + return 1 + }() + } + + wg.Wait() +} diff --git a/gee-cache/day7-proto-buf/geecache/singleflight/singleflight_test.go b/gee-cache/day7-proto-buf/geecache/singleflight/singleflight_test.go index 450951a..44c865d 100644 --- a/gee-cache/day7-proto-buf/geecache/singleflight/singleflight_test.go +++ b/gee-cache/day7-proto-buf/geecache/singleflight/singleflight_test.go @@ -1,11 +1,14 @@ package singleflight import ( + "sync" "testing" + "time" ) func TestDo(t *testing.T) { var g Group + v, err := g.Do("key", func() (interface{}, error) { return "bar", nil }) @@ -14,3 +17,29 @@ func TestDo(t *testing.T) { t.Errorf("Do v = %v, error = %v", v, err) } } + +func TestGoDo(t *testing.T) { + var g Group + wg := sync.WaitGroup{} + + times := 10 + wg.Add(times) + for i := 0; i < times; i++ { + go func() interface{} { + v, err := g.Do("key", func() (interface{}, error) { + time.Sleep(time.Millisecond * 50) + return "bar", nil + }) + + wg.Done() + + if v != "bar" || err != nil { + t.Errorf("Do v = %v, error = %v", v, err) + } + + return 1 + }() + } + + wg.Wait() +}