-
Notifications
You must be signed in to change notification settings - Fork 0
/
Assigment2DataRaces.cpp
68 lines (54 loc) · 1.1 KB
/
Assigment2DataRaces.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
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <thread>
using namespace std;
/*
Write a task function that increments a global int variable 100,000 times in a for loop.
Write a program that runs this function in concurrent threads. When all the threads have completed execution, print out the final value of the
counter.
Increase the number of threads until you see anomalous results.
Questions for this assignment
Implement the program as described. Check that your program compiles and runs.
Why does the program appear to give an incorrect result?
*/
int counter = 0;
int main()
{
thread t1([]() {
for (int i = 0; i < 100000; i++)
{
counter++;
}
});
thread t2([]() {
for (int i = 0; i < 100000; i++)
{
counter++;
}
});
thread t3([]() {
for (int i = 0; i < 100000; i++)
{
counter++;
}
});
thread t4([]() {
for (int i = 0; i < 100000; i++)
{
counter++;
}
});
thread t5([]() {
for (int i = 0; i < 100000; i++)
{
counter++;
}
});
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
cout << "Counter: " << counter << endl;
return 0;
}