-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path00_basics_of_threads.cpp
More file actions
66 lines (53 loc) · 1.26 KB
/
00_basics_of_threads.cpp
File metadata and controls
66 lines (53 loc) · 1.26 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
/* Thread is a light weight process used to achieve parallelism by dividing a process to multiple threads
Eg:
1) Browser having multiple tabs
2) MS word uses multiple threads, one for format, other for spellcheck
NOTE: The thread execution order is not defined, it can be any order
*/
#include <iostream>
#include <thread>
#include <chrono>
#include <algorithm>
using namespace std;
using namespace std::chrono;
typedef unsigned long long ull;
ull oddSum = 0, evenSum = 0;
void findEven(ull start, ull end)
{
for (ull i = start; i <= end; i++)
{
if (!(i & 1))
{
evenSum += i;
}
}
}
void findOdd(ull start, ull end)
{
for (ull i = start; i <= end; i++)
{
if (i & 1)
{
oddSum += i;
}
}
}
int main()
{
ull start = 0, end = 1900000000;
auto startTime = high_resolution_clock::now();
// multi-threading
// Create thread using Function Pointers
std::thread t1(findOdd, start, end);
std::thread t2(findEven, start, end);
// findOdd(start, end);
// findEven(start, end);
t1.join();
t2.join();
auto stopTime = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stopTime - startTime);
cout << "Odd Sum " << oddSum << "\n";
cout << "Even Sum " << evenSum << "\n";
cout << "Time taken is " << duration.count() << "\n";
return 0;
}