-
Notifications
You must be signed in to change notification settings - Fork 25
/
foo.cpp
39 lines (34 loc) · 795 Bytes
/
foo.cpp
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
#include <array>
#include <cstddef>
#include <exception>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
namespace {
struct Counter {
std::mutex mtx;
std::size_t impl = 0;
};
void do_something(Counter& counter) {
std::lock_guard<std::mutex> lck{counter.mtx};
++counter.impl;
std::cout << "Doing something #" << counter.impl << '\n';
}
}
int main() {
try {
Counter counter;
std::array<std::thread, 3> workers;
for (auto& worker : workers) {
worker = std::thread{&do_something, std::ref(counter)};
}
for (auto& worker : workers) {
worker.join();
}
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
return 1;
}
return 0;
}