forked from cirosantilli/cpp-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.cpp
More file actions
73 lines (68 loc) · 1.78 KB
/
mutex.cpp
File metadata and controls
73 lines (68 loc) · 1.78 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
// Only allows one thread to enter the critical zone.
//
// Usage:
//
// ./mutex.out [num_iters [num_threads [use_mutex=0|1]]
//
// Should work because uses mutex:
//
// ./mutex.out 1000 10 1
//
// Fails for large num_iters large enough with more than one thread
// due to synchroniation problems:
//
// ./mutex.out 1000 10 0
//
// This is an artificial example: the more restricted and efficient atomic would be a better fit.
//
// http://stackoverflow.com/questions/6837699/are-mutex-lock-functions-sufficient-without-volatile
#if __cplusplus >= 201103L
#include <cassert>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
std::mutex mutex;
unsigned int num_threads;
unsigned int use_mutex = 1;
unsigned long global = 0;
unsigned long long num_iters = 0;
void thread_main() {
for (decltype(num_iters) i = 0; i < num_iters; ++i) {
if (use_mutex)
mutex.lock();
global++;
if (use_mutex)
mutex.unlock();
}
}
#endif
int main(int argc, char **argv) {
#if __cplusplus >= 201103L
if (argc > 1) {
num_iters = std::strtoull(argv[1], NULL, 10);
} else {
num_iters = 10;
}
if (argc > 2) {
num_threads = std::strtoull(argv[2], NULL, 10);
} else {
num_threads = std::thread::hardware_concurrency();
}
if (argc > 3) {
use_mutex = (argv[3][0] == '1');
} else {
use_mutex = 1;
}
std::vector<std::thread> threads(num_threads);
for (auto& thread : threads)
thread = std::thread(thread_main);
for (auto& thread : threads)
thread.join();
auto num_ops = num_threads * num_iters;
if (global != num_ops) {
std::cout << "fraction of errors " << ((double)global / num_ops) << std::endl;
assert(false);
}
#endif
}