shapeio icon indicating copy to clipboard operation
shapeio copied to clipboard

potential race condition

Open lestrrat opened this issue 9 years ago • 1 comments

以下のテストを追加してgo test -race すると色々でてきます。

そもそもこういう使い方はありえないのかもしれませんが、最近こういうのを自分のコードで見つけるのに凝ってるので…

diff --git a/shapeio_test.go b/shapeio_test.go
index bd9b545..32d4e09 100644
--- a/shapeio_test.go
+++ b/shapeio_test.go
@@ -2,10 +2,12 @@ package shapeio_test

 import (
        "bytes"
+       "context"
        "io"
        "io/ioutil"
        "net/http"
        "os"
+       "sync"
        "testing"
        "time"

@@ -101,3 +103,50 @@ func TestWrite(t *testing.T) {
                }
        }
 }
+
+func TestConcurrentSetRateLimit(t *testing.T) {
+       // run with go test -race
+       ctx, cancel := context.WithCancel(context.Background())
+       var wg sync.WaitGroup
+
+       sio := shapeio.NewWriter(ioutil.Discard)
+
+       for _, l := range rates {
+               limit := l
+               wg.Add(1)
+               go func() {
+                       defer wg.Done()
+                       t := time.NewTicker(50 * time.Millisecond)
+                       defer t.Stop()
+                       for {
+                               select {
+                               case <-ctx.Done():
+                                       return
+                               case <-t.C:
+                                       sio.SetRateLimit(limit)
+                               }
+                       }
+               }()
+       }
+
+       wg.Add(1)
+       go func() {
+               defer wg.Done()
+               t := time.NewTicker(50 * time.Millisecond)
+               defer t.Stop()
+               for {
+                       select {
+                       case <-ctx.Done():
+                               return
+                       case <-t.C:
+                               for _, src := range srcs {
+                                       io.Copy(sio, src)
+                               }
+                       }
+               }
+       }()
+
+       time.AfterFunc(time.Second, cancel)
+
+       wg.Wait()
+}

lestrrat avatar Sep 16 '16 12:09 lestrrat

I don't think this is an issue with shapeio. It is just a simple library - it is up to the caller to handle synchronisation issues.

porjo avatar Jan 28 '19 05:01 porjo