Skip to content

potential race condition #2

@lestrrat

Description

@lestrrat

以下のテストを追加して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()
+}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions