From 879e5af02cfb6ab81702e78a869cc92c92614f89 Mon Sep 17 00:00:00 2001 From: Achille Roussel Date: Tue, 19 Sep 2023 10:49:54 -0700 Subject: [PATCH] add tests for goroutine local storage Signed-off-by: Achille Roussel --- gls_test.go | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 gls_test.go diff --git a/gls_test.go b/gls_test.go new file mode 100644 index 0000000..50916b4 --- /dev/null +++ b/gls_test.go @@ -0,0 +1,70 @@ +package coroutine + +import "testing" + +func TestGLS(t *testing.T) { + c := make(chan int) + + f := func(n int) { + defer close(c) + storeContext(getg(), n) + + load := func() int { + v, _ := loadContext(getg()).(int) + return v + } + + c <- load() + clearContext(getg()) + c <- load() + } + + go f(42) + + if v, ok := <-c; !ok || v != 42 { + t.Errorf("unexpected first value: want=(42,true) got=(%v,%v)", v, ok) + } + if v, ok := <-c; !ok || v != 0 { + t.Errorf("unexpected second value: want=(0,true) got=(%v,%v)", v, ok) + } + if v, ok := <-c; ok { + t.Errorf("too many values received: want=(0,false) got=(%v,%v)", v, ok) + } +} + +func BenchmarkGLS(b *testing.B) { + b.Run("getg", func(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _ = getg() + } + }) + }) + + b.Run("loadContext", func(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + g := getg() + for pb.Next() { + _ = loadContext(g) + } + }) + }) + + b.Run("storeContext", func(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + g := getg() + for pb.Next() { + storeContext(g, 42) + } + }) + }) + + b.Run("clearContext", func(b *testing.B) { + b.RunParallel(func(pb *testing.PB) { + g := getg() + for pb.Next() { + clearContext(g) + } + }) + }) +}