-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrylock_test.cpp
More file actions
100 lines (79 loc) · 2.3 KB
/
trylock_test.cpp
File metadata and controls
100 lines (79 loc) · 2.3 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// (C) Copyright 2013 Andrey
// (C) Copyright 2013 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// This performance test is based on the performance test provided by
// maxim.yegorushkin at https://svn.boost.org/trac/boost/ticket/7422
#include "simple_stopwatch.hpp"
#define BOOST_THREAD_VERSION 4
#define BOOST_THREAD_USES_CHRONO
#include <boost/thread/lock_guard.hpp>
#include <boost/thread/lock_types.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread_only.hpp>
#include <iostream>
#ifdef DEBUG
# define VERBOSE
#endif
namespace
{
using namespace boost;
mutex mtx; // warning: initialization of 'mutex' with static storage duration
// may throw an exception that cannot be caught [cert-err58-cpp]
int counter = 0;
const int cycles = 1000;
const int worker = 2;
void monitor()
{
do {
boost::this_thread::sleep_for(ns(50));
{
unique_lock<mutex> lock(mtx, defer_lock);
if (lock.try_lock()) {
std::cout << counter << std::endl;
if (counter >= (worker * cycles)) {
break;
}
}
}
} while (true);
}
void unique()
{
int cycle(0);
while (++cycle <= cycles) {
unique_lock<mutex> lock(mtx);
++counter;
}
}
} // namespace
int main()
{
using namespace boost;
Stopwatch::duration best_time(std::numeric_limits<Stopwatch::rep>::max
BOOST_PREVENT_MACRO_SUBSTITUTION());
for (int i = 100; i > 0; --i) {
Stopwatch timer;
thread t1(unique);
thread t2(unique);
thread tm(monitor);
t1.join();
t2.join();
tm.join();
Stopwatch::duration elapsed(timer.elapsed());
#ifdef VERBOSE
std::cout << " Time spent: "
<< chrono::duration_fmt(chrono::duration_style::symbol)
<< elapsed << std::endl;
#endif
best_time =
std::min BOOST_PREVENT_MACRO_SUBSTITUTION(best_time, elapsed);
}
std::cout << "Best Time spent: " << best_time << std::endl;
std::cout << "Time spent/cycle:" << best_time / cycles / worker
<< std::endl;
return 0;
}