-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcondition_variable.cpp
More file actions
60 lines (57 loc) · 1.37 KB
/
condition_variable.cpp
File metadata and controls
60 lines (57 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// Created by Administrator on 2023/10/15.
//
#include <benchmark/benchmark.h>
#include <condition_variable>
#include <mutex>
#include <thread>
static std::condition_variable cv;
static std::mutex mu;
std::atomic_bool bRun = true;
void thread_wait()
{
std::unique_lock lock(mu);
do
{
cv.wait(lock);
} while (bRun.load(std::memory_order_acquire));
}
template <size_t wait> static void BenchCondition(benchmark::State &state)
{
int n = 0;
for (auto _ : state)
{
if constexpr (wait == 0)
{
cv.notify_one();
}
else if (wait == 1)
{
{
std::unique_lock lock(mu);
benchmark::DoNotOptimize(lock);
}
cv.notify_one();
}
else
{
std::unique_lock lock(mu);
benchmark::DoNotOptimize(lock);
cv.notify_one();
}
}
benchmark::DoNotOptimize(n);
}
BENCHMARK_TEMPLATE(BenchCondition, 0);
BENCHMARK_TEMPLATE(BenchCondition, 1);
BENCHMARK_TEMPLATE(BenchCondition, 2);
int main(int argc, char **argv)
{
std::thread waiter(thread_wait);
benchmark::Initialize(&argc, argv);
benchmark::RunSpecifiedBenchmarks();
bRun.store(false, std::memory_order_release);
cv.notify_one();
waiter.join();
return 0;
}