File tree 2 files changed +35
-1
lines changed
2 files changed +35
-1
lines changed Original file line number Diff line number Diff line change 5
5
#include " src/common/random.h"
6
6
#include " src/common/platform/fork.h"
7
7
8
+ #include < atomic>
8
9
#include < cstring>
9
10
#include < random>
10
11
@@ -26,12 +27,17 @@ class TlsRandomNumberGenerator
26
27
TlsRandomNumberGenerator () noexcept
27
28
{
28
29
Seed ();
29
- platform::AtFork (nullptr , nullptr , OnFork);
30
+ if (!flag.test_and_set ())
31
+ {
32
+ platform::AtFork (nullptr , nullptr , OnFork);
33
+ }
30
34
}
31
35
32
36
static FastRandomNumberGenerator &engine () noexcept { return engine_; }
33
37
34
38
private:
39
+ static std::atomic_flag flag;
40
+
35
41
static thread_local FastRandomNumberGenerator engine_;
36
42
37
43
static void OnFork () noexcept { Seed (); }
@@ -44,6 +50,7 @@ class TlsRandomNumberGenerator
44
50
}
45
51
};
46
52
53
+ std::atomic_flag TlsRandomNumberGenerator::flag;
47
54
thread_local FastRandomNumberGenerator TlsRandomNumberGenerator::engine_{};
48
55
} // namespace
49
56
Original file line number Diff line number Diff line change 4
4
#include " src/common/random.h"
5
5
6
6
#include < algorithm>
7
+ #include < atomic>
7
8
#include < iterator>
9
+ #include < thread>
10
+ #include < vector>
8
11
9
12
#include < gtest/gtest.h>
10
13
using opentelemetry::sdk::common::Random;
@@ -34,3 +37,27 @@ TEST(RandomTest, GenerateRandomBuffer)
34
37
std::equal (std::begin (buf1_vector), std::end (buf1_vector), std::begin (buf2_vector)));
35
38
}
36
39
}
40
+
41
+ void doSomethingOnce (std::atomic_uint *count)
42
+ {
43
+ static std::atomic_flag flag;
44
+ if (!flag.test_and_set ())
45
+ {
46
+ (*count)++;
47
+ }
48
+ }
49
+
50
+ TEST (RandomTest, AtomicFlagMultiThreadTest)
51
+ {
52
+ std::vector<std::thread> threads;
53
+ std::atomic_uint count (0 );
54
+ for (int i = 0 ; i < 10 ; ++i)
55
+ {
56
+ threads.push_back (std::thread (doSomethingOnce, &count));
57
+ }
58
+ for (auto &t : threads)
59
+ {
60
+ t.join ();
61
+ }
62
+ EXPECT_EQ (1 , count.load ());
63
+ }
You can’t perform that action at this time.
0 commit comments