-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathatomic.cpp
77 lines (67 loc) · 1.27 KB
/
atomic.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
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
#include <atomic>
#include <thread>
#include <iostream>
#include <vector>
struct AtomicCounter
{
std::atomic<int> counter;
AtomicCounter()
{
counter = 0;
}
void increment(void)
{
++counter;
}
void decrement(void)
{
counter--;
}
};
struct Counter
{
int counter;
Counter()
{
counter = 0;
}
void increment(void)
{
++counter;
}
void decrement(void)
{
counter--;
}
};
int main()
{
std::vector<std::thread> non_atom;
std::vector<std::thread> atom;
Counter count;
AtomicCounter a_count;
std::cout << "Count from 0 to 100 NON ATOMIC COUNTER in 5 threads" << std::endl;
for (int i = 0; i < 5; i++)
{
non_atom.push_back(std::thread([&count] {
for (int j = 0; j < 100; j++)
count.increment();
}));
}
for (int i = 0; i < 5; i++)
non_atom[i].join();
std::cout << "RESULT: " << count.counter << std::endl;
std::cout << "Count from 0 to 500 ATOMIC COUNTER in 5 threads" << std::endl;
for (int i = 0; i < 5; i++)
{
atom.push_back(std::thread([&a_count] {
for (int j = 0; j < 100; j++)
a_count.increment();
}));
}
for (int i = 0; i < 5; i++)
atom[i].join();
std::cout << "RESULT: " << a_count.counter << std::endl;
std::cin.get();
return (0);
}