Skip to content

Commit 1d31093

Browse files
committed
fix tsan: utiltime race on nMockTime
1 parent 321bbc2 commit 1d31093

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/utiltime.cpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,17 @@
99

1010
#include "utiltime.h"
1111

12+
#include <atomic>
13+
1214
#include <boost/date_time/posix_time/posix_time.hpp>
1315
#include <boost/thread.hpp>
1416

15-
static int64_t nMockTime = 0; //!< For unit testing
17+
static std::atomic<int64_t> nMockTime(0); //!< For unit testing
1618

1719
int64_t GetTime()
1820
{
19-
if (nMockTime) return nMockTime;
21+
int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
22+
if (mocktime) return mocktime;
2023

2124
time_t now = time(NULL);
2225
assert(now > 0);
@@ -25,7 +28,7 @@ int64_t GetTime()
2528

2629
void SetMockTime(int64_t nMockTimeIn)
2730
{
28-
nMockTime = nMockTimeIn;
31+
nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
2932
}
3033

3134
int64_t GetTimeMillis()
@@ -52,7 +55,8 @@ int64_t GetSystemTimeInSeconds()
5255
/** Return a time useful for the debug log */
5356
int64_t GetLogTimeMicros()
5457
{
55-
if (nMockTime) return nMockTime*1000000;
58+
int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
59+
if (mocktime) return mocktime*1000000;
5660

5761
return GetTimeMicros();
5862
}

0 commit comments

Comments
 (0)