Skip to content

Commit 6765091

Browse files
author
antoshkka
committed
feat util: fix ThreadSanitizer reported data race
``` WARNING: ThreadSanitizer: data race (pid=123179) Read of size 8 at 0x0000065aad98 by thread T14: #0 NSystemInfo::CachedNumberOfCpus() util/system/info.cpp:241:10 (taxi-uservices-userver-core-tests+0x4155bba) #1 engine::(anonymous namespace)::TaskProcessorThreadStartedHook() userver/core/src/engine/task/task_processor.cpp:100:15 (taxi-uservices-userver-core-tests+0x5306bc8) ydb-platform#2 engine::TaskProcessor::PrepareWorkerThread(unsigned long) userver/core/src/engine/task/task_processor.cpp:347:5 (taxi-uservices-userver-core-tests+0x5306bc8) ``` The change on a hot path is equivalent to the previously compiler generated x86 code (just a `load` instruction). On other platforms this could actually fix a data race. commit_hash:acb1fe1b8f3075cc27b18aab4f1bd0b88292c270
1 parent 689931d commit 6765091

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

util/system/info.cpp

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include "error.h"
44
#include "fs.h"
55

6+
#include <atomic>
67
#include <cmath>
78
#include <cstdlib>
89

@@ -234,23 +235,27 @@ size_t NSystemInfo::LoadAverage(double* la, size_t len) {
234235
return (size_t)ret;
235236
}
236237

237-
static size_t NCpus;
238-
static size_t NMillicores;
238+
static std::atomic<size_t> NCpus{0};
239+
static std::atomic<size_t> NMillicores{0};
239240

240241
size_t NSystemInfo::CachedNumberOfCpus() {
241-
if (!NCpus) {
242-
NCpus = NumberOfCpus();
242+
auto ncpus_snapshot = NCpus.load();
243+
if (!ncpus_snapshot) {
244+
ncpus_snapshot = NumberOfCpus();
245+
NCpus = ncpus_snapshot;
243246
}
244247

245-
return NCpus;
248+
return ncpus_snapshot;
246249
}
247250

248251
size_t NSystemInfo::CachedNumberOfMillicores() {
249-
if (!NMillicores) {
250-
NMillicores = NumberOfMillicores();
252+
auto nmillicores_snapshot = NMillicores.load();
253+
if (!nmillicores_snapshot) {
254+
nmillicores_snapshot = NumberOfMillicores();
255+
NMillicores = nmillicores_snapshot;
251256
}
252257

253-
return NMillicores;
258+
return nmillicores_snapshot;
254259
}
255260

256261
size_t NSystemInfo::GetPageSize() noexcept {

0 commit comments

Comments
 (0)