From a45511bb196054059456cc6d7dd0a16f87fc52f2 Mon Sep 17 00:00:00 2001 From: Juan Batiz-Benet Date: Wed, 5 Nov 2014 08:49:55 -0800 Subject: [PATCH] fixed dht race #270 --- dht_test.go | 4 ++-- ext_test.go | 19 +++++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/dht_test.go b/dht_test.go index 3748e65193a..ffbbef81981 100644 --- a/dht_test.go +++ b/dht_test.go @@ -417,14 +417,14 @@ func TestConnectCollision(t *testing.T) { done := make(chan struct{}) go func() { - _, err = dhtA.Connect(ctx, peerB) + _, err := dhtA.Connect(ctx, peerB) if err != nil { t.Fatal(err) } done <- struct{}{} }() go func() { - _, err = dhtB.Connect(ctx, peerA) + _, err := dhtB.Connect(ctx, peerA) if err != nil { t.Fatal(err) } diff --git a/ext_test.go b/ext_test.go index 19275338da2..a6d1d933d97 100644 --- a/ext_test.go +++ b/ext_test.go @@ -16,6 +16,7 @@ import ( pb "github.com/jbenet/go-ipfs/routing/dht/pb" u "github.com/jbenet/go-ipfs/util" + "sync" "time" ) @@ -28,15 +29,24 @@ type mesHandleFunc func(msg.NetMessage) msg.NetMessage // fauxNet is a standin for a swarm.Network in order to more easily recreate // different testing scenarios type fauxSender struct { + sync.Mutex handlers []mesHandleFunc } func (f *fauxSender) AddHandler(fn func(msg.NetMessage) msg.NetMessage) { + f.Lock() + defer f.Unlock() + f.handlers = append(f.handlers, fn) } func (f *fauxSender) SendRequest(ctx context.Context, m msg.NetMessage) (msg.NetMessage, error) { - for _, h := range f.handlers { + f.Lock() + handlers := make([]mesHandleFunc, len(f.handlers)) + copy(handlers, f.handlers) + f.Unlock() + + for _, h := range handlers { reply := h(m) if reply != nil { return reply, nil @@ -52,7 +62,12 @@ func (f *fauxSender) SendRequest(ctx context.Context, m msg.NetMessage) (msg.Net } func (f *fauxSender) SendMessage(ctx context.Context, m msg.NetMessage) error { - for _, h := range f.handlers { + f.Lock() + handlers := make([]mesHandleFunc, len(f.handlers)) + copy(handlers, f.handlers) + f.Unlock() + + for _, h := range handlers { reply := h(m) if reply != nil { return nil