-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_Multithreading_intro.cpp
More file actions
80 lines (61 loc) · 2.34 KB
/
Copy path1_Multithreading_intro.cpp
File metadata and controls
80 lines (61 loc) · 2.34 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
// TOPIC: Introduction to thread in c++ (c++11)
// QUESTIONS
// 1. What do you understand by thread and give one example in C++?
// ANSWER
// 0. In evey application there is a default thread which is main(), in side this we create other threads.
// 1. A thread is also known as lightweight process. Idea is achieve parallelism by dividing a process into multiple threads.
// For example:
// (a) The browser has multiple tabs that can be different threads.
// (b) MS Word must be using multiple threads, one thread to format the text, another thread to process inputs (spell checker)
// (c) Visual Studio code editor would be using threading for auto completing the code. (Intellicence)
// WAYS TO CREATE THREADS IN C++11
// 1. Function Pointers
// 2. Lambda Functions
// 3. Functors
// 4. Member Functions
// 5. Static Member functions
// REQUIREMENT
// Find the addition of all odd number from 1 to 1900000000 and all even number from 1 to 1900000000
#include <iostream>
#include <thread>
#include <chrono>
#include <algorithm>
using namespace std;
using namespace std::chrono;
typedef long long int ull;
void findEven(ull start, ull end, ull* EvenSum) {
for (ull i = start; i <= end; ++i){
if (!(i & 1)){
*(EvenSum) += i;
}
}
}
void findOdd(ull start, ull end, ull* OddSum) {
for (ull i = start; i <= end; ++i){
if (i & 1){
(*OddSum) += i;
}
}
}
int main() {
ull start = 0, end = 1900000000;
ull OddSum = 0;
ull EvenSum = 0;
auto startTime = high_resolution_clock::now();
// without Thread, only one thread, i.e, main thread will be their.
// findOdd(start, end);
// findEven(start, end);
// // WITH THREAD
std::thread t1(findEven, start, end, &(EvenSum));
std::thread t2(findOdd, start, end, &(OddSum));
// `It is a member function that makes sure that the execution of the thread is complete before moving on to the next statement after the join() function call.
t1.join();
t2.join();
auto stopTime = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stopTime - startTime);
cout << "OddSum : " << OddSum << endl;
cout << "EvenSum : " << EvenSum << endl;
cout << "Sec: " << duration.count()/1000000 << endl;
// 4Sec (Without thread) | 2 Sec(With thread) bcz both t1 and t2 running parallely & main thread waits to complere their process.
return 0;
}