-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiThreadingAverage.cpp
More file actions
95 lines (62 loc) · 2.07 KB
/
multiThreadingAverage.cpp
File metadata and controls
95 lines (62 loc) · 2.07 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Created by
Ethan Roberts
CS 415 Operating Systems
This is a multi-threaded program that averages two data-sets
together using eight different threads.
Compiled using: g++ -g -pthread multiThreadAverage.cpp -o output
*/
#include <iostream>
#include <thread>
using namespace std;
#define MAXSIZE 10000000
void arrayAverage(int *dataset1, int *dataset2, int *resultset, int size)
{
// 8 partitions will run this meaning each thread will
// process 1,250,000 elements each
for (int i = (size - 1250000); i < size; ++i){
resultset[i] = ((dataset1[i] + dataset2[i])/2);
}
}
int main()
{
int *dataset1 = new int[MAXSIZE];
int *dataset2 = new int[MAXSIZE];
int *resultset = new int[MAXSIZE];
//clearing all arrays before using
for (int i = 0; i < MAXSIZE; ++i){
dataset1[i] = 0;
dataset2[i] = 0;
resultset[i] = 0;
}
//filling data-sets with values
for (int i = 0; i < MAXSIZE; ++i){
dataset1[i] = (i * 2);
dataset2[i] = (i * 3);
}
thread t1(arrayAverage,dataset1,dataset2,resultset,((MAXSIZE / 8) * 1));
thread t2(arrayAverage,dataset1,dataset2,resultset,((MAXSIZE / 8) * 2));
thread t3(arrayAverage,dataset1,dataset2,resultset,((MAXSIZE / 8) * 3));
thread t4(arrayAverage,dataset1,dataset2,resultset,((MAXSIZE / 8) * 4));
thread t5(arrayAverage,dataset1,dataset2,resultset,((MAXSIZE / 8) * 5));
thread t6(arrayAverage,dataset1,dataset2,resultset,((MAXSIZE / 8) * 6));
thread t7(arrayAverage,dataset1,dataset2,resultset,((MAXSIZE / 8) * 7));
thread t8(arrayAverage,dataset1,dataset2,resultset,((MAXSIZE / 8) * 8));
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
t7.join();
t8.join();
//** Uncomment code below to print all 10 million averages
//** inside "resultset"
// for (int i = 0; i < MAXSIZE; ++i)
// cout << "Average of index " << i << ": " << resultset[i] << "\n";
//printing 200 elements to prove the code is accurate
for (int i = 0; i < 200; ++i){
cout << "Average of index " << i << ": " << resultset[i] << "\n";
}
return 0;
}