-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy paththread_ex4.cpp
67 lines (56 loc) · 1.37 KB
/
thread_ex4.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
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
using namespace std;
void echo(atomic<int>& num) {
for(int i=0; i<100; i++)
{
++num;
this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
int main()
{
int i=0;
while(i<20)
{
atomic<int> counter(0);
// Create a vector of threads instead of a simple array of threads | safer
vector<thread> threads;
// Call the echo function with the counter parameter by reference using ref()
for(auto i=0; i<10; i++)
threads.push_back(thread(echo, ref(counter)));
// Join, if joinable()
for(auto& th : threads)
if(th.joinable())
th.join();
// Print-out the counter
cout << "Counter = " << counter << endl;
i++;
}
return 0;
}
/* OUTPUT || Thread-Safe using atomic || atomic variable 'counter' cannot be interrupted by every thread
It is loaded, incremented and stored back || pitfall --> atomic introduces low performance, like it is not threaded at all!
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
Counter = 1000
*/