Skip to content
This repository was archived by the owner on Sep 6, 2022. It is now read-only.

Commit 7a741a9

Browse files
committed
use a lock
1 parent 375d7b4 commit 7a741a9

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

peer/record.go

+12-10
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package peer
22

33
import (
44
"fmt"
5-
"sync/atomic"
5+
"sync"
66
"time"
77

88
pb "github.com/libp2p/go-libp2p-core/peer/pb"
@@ -126,20 +126,22 @@ func PeerRecordFromProtobuf(msg *pb.PeerRecord) (*PeerRecord, error) {
126126
return record, nil
127127
}
128128

129-
var lastTimestamp uint64
129+
var (
130+
lastTimestampMu sync.Mutex
131+
lastTimestamp uint64
132+
)
130133

131134
// TimestampSeq is a helper to generate a timestamp-based sequence number for a PeerRecord.
132135
func TimestampSeq() uint64 {
133136
now := uint64(time.Now().UnixNano())
134-
previous := atomic.LoadUint64(&lastTimestamp)
135-
// If the new time is not greater than the last tiemstamp, or if someone else beats us to
136-
// updateing the timestamp, just use last+1.
137-
//
138-
// Technically, last+1 could be before "now". But it's still strictly increasing and close
139-
// enough.
140-
if now <= previous || !atomic.CompareAndSwapUint64(&lastTimestamp, previous, now) {
141-
now = atomic.AddUint64(&lastTimestamp, 1)
137+
lastTimestampMu.Lock()
138+
defer lastTimestampMu.Unlock()
139+
// Not all clocks are strictly increasing, but we need these sequence numbers to be strictly
140+
// increasing.
141+
if now <= lastTimestamp {
142+
now = lastTimestamp + 1
142143
}
144+
lastTimestamp = now
143145
return now
144146
}
145147

0 commit comments

Comments
 (0)