-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultithreading2.cpp
More file actions
49 lines (45 loc) · 1.55 KB
/
multithreading2.cpp
File metadata and controls
49 lines (45 loc) · 1.55 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
//g++ -std=c++11 -pthread -g -o multithreads2 semaphore.cpp multithreading2.cpp
#include"semaphore.h"
#include<iostream>
#include<thread>
#include<chrono>
using namespace std;
semaphore t(0);
void printid(int id) {
cout << "Thread " << id << " Yay ! Just spawned, calling t.wait()" << endl;
t.wait();
cout << "Thread " << id << endl;
// cout << "Thread " << id << " Yay ! Finished job calling t.notify()" << endl;
// cout << "Thread " << id << " Yay ! Exiting without calling t.notify()" << endl;
// t.notify();
}
int main(int argc, char* argv[]) {
thread threads[5];
cout << "Main thread : Initial Semaphore count is " << t.returnCount() << endl;
for (int i=0; i<5; i++) {
threads[i] = thread(printid, i+1);
}
cout << "Main thread : Spawned threads ! Now Sleeping for 5 seconds" << endl;
this_thread::sleep_for (chrono::seconds(5));
cout << "Main thread : Awake from sleep, now calling t.notify" << endl;
for (auto& th : threads) {
t.notify();
}
for (auto& th : threads) {
th.join();
}
cout << "Main thread : Final Semaphore count is " << t.returnCount() << endl;
cout << "Main thread : Initial Semaphore count is " << t.returnCount() << endl;
for (int i=0; i<5; i++) {
threads[i] = thread(printid, i+1);
}
cout << "Main thread : Spawned threads ! Now Sleeping for 5 seconds" << endl;
this_thread::sleep_for (chrono::seconds(5));
cout << "Main thread : Awake from sleep, now calling t.notify(#)" << endl;
t.notify(5);
for (auto& th : threads) {
th.join();
}
cout << "Main thread : Final Semaphore count is " << t.returnCount() << endl;
return 0;
}