blob: 060415f6dc7d194e1f76e2790ab546ad4a08fab8 (
plain) (
blame)
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
|
#include <owning_mutex.h>
#include <limits>
#include <thread>
#include <vector>
#include <cassert>
#include <cstdio>
constexpr unsigned kNumThreads = 8;
constexpr unsigned kIter = 1 << 18;
static_assert((static_cast<unsigned long>(kNumThreads) *
static_cast<unsigned long>(kIter)) <=
std::numeric_limits<unsigned>::max(),
"Expectate result overflowed!");
int main() {
owning_mutex<unsigned> data(0u);
std::vector<std::thread> threads;
threads.reserve(kNumThreads);
for (unsigned t = 0; t < kNumThreads; ++t) {
threads.emplace_back([&data, t]() {
for (unsigned i = 0; i < kIter; ++i) {
*data.lock() += 1;
}
std::printf("th%u finished\n", t);
});
}
for (auto& th : threads) {
th.join();
}
assert(*data.lock() == (kNumThreads * kIter));
std::printf("Result %u\n", *data.lock());
return 0;
}
|