@cryptotaxi247 / kubo / commits / c43e8fa35

fixing race in testutil port

Juan Batiz-Benet committed Dec 23, 2014 at 17:59 UTC c43e8fa35b4a2fd0fafbd878e6112ff128b5404a
1 file changed +13 -5
util/testutil/gen.go
+13 -5
@@ -6,6 +6,7 @@ import (
6 "errors"
7 "fmt"
8 "io"
9 + "sync"
10 "testing"
11
12 ci "github.com/jbenet/go-ipfs/crypto"
@@ -49,17 +50,24 @@ func RandLocalTCPAddress() ma.Multiaddr {
50 // most ports above 10000 aren't in use by long running processes, so yay.
51 // (maybe there should be a range of "loopback" ports that are guaranteed
52 // to be open for the process, but naturally can only talk to self.)
52 - if lastPort == 0 {
53 - lastPort = 10000 + SeededRand.Intn(50000)
53 +
54 + lastPort.Lock()
55 + if lastPort.port == 0 {
56 + lastPort.port = 10000 + SeededRand.Intn(50000)
57 }
55 - lastPort++
58 + port := lastPort.port
59 + lastPort.port++
60 + lastPort.Unlock()
61
57 - addr := fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", lastPort)
62 + addr := fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", port)
63 maddr, _ := ma.NewMultiaddr(addr)
64 return maddr
65 }
66
62 -var lastPort = 0
67 +var lastPort = struct {
68 + port int
69 + sync.Mutex
70 +}{}
71
72 // PeerNetParams is a struct to bundle together the four things
73 // you need to run a connection with a peer: id, 2keys, and addr.