This repository was archived by the owner on Sep 6, 2022. It is now read-only.
File tree 1 file changed +12
-10
lines changed
1 file changed +12
-10
lines changed Original file line number Diff line number Diff line change @@ -2,7 +2,7 @@ package peer
2
2
3
3
import (
4
4
"fmt"
5
- "sync/atomic "
5
+ "sync"
6
6
"time"
7
7
8
8
pb "github.com/libp2p/go-libp2p-core/peer/pb"
@@ -126,20 +126,22 @@ func PeerRecordFromProtobuf(msg *pb.PeerRecord) (*PeerRecord, error) {
126
126
return record , nil
127
127
}
128
128
129
- var lastTimestamp uint64
129
+ var (
130
+ lastTimestampMu sync.Mutex
131
+ lastTimestamp uint64
132
+ )
130
133
131
134
// TimestampSeq is a helper to generate a timestamp-based sequence number for a PeerRecord.
132
135
func TimestampSeq () uint64 {
133
136
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
142
143
}
144
+ lastTimestamp = now
143
145
return now
144
146
}
145
147
You can’t perform that action at this time.
0 commit comments