-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_comp.cpp
More file actions
36 lines (31 loc) · 878 Bytes
/
thread_comp.cpp
File metadata and controls
36 lines (31 loc) · 878 Bytes
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
// C++ Usage of thread-safe type.
#include <atomic>
#include <thread>
#include <vector>
#include <iostream>
// A very simple thread-safe type.
class ThreadSafeCounter {
public:
ThreadSafeCounter() : counter_(0) {}
void Increment() { counter_.fetch_add(1); }
int GetCount() const { return counter_; }
private:
std::atomic_int32_t counter_;
};
int main() {
ThreadSafeCounter counter;
const int n = 10;
std::vector<std::thread> threads;
// Spawn `n` threads that all share a single counter.
for (int i = 0; i < n; i++) {
threads.push_back(std::thread([&counter] {
// Unsynchronized call of a non-const method.
// Only safe because the type is thread-safe.
counter.Increment();
}));
}
for (auto& thread : threads) { thread.join(); }
// This will ultimately print `n`.
std::cout << counter.GetCount() << "\n";
return 0;
}