-
Notifications
You must be signed in to change notification settings - Fork 3
/
Semaphores.cpp
67 lines (54 loc) · 1.26 KB
/
Semaphores.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
#include "Semaphores.h"
#include <iostream>
using namespace std;
Semaphore::Semaphore(){
this->value = 99;
}
Semaphore::Semaphore(const int& n) {
this->value = n;
}
void Semaphore::wait(const shared_ptr<PCB>& pcb) {
this->value--;
if (this->value < 0) {
this->blocked = true;
block(pcb);
}
}
void Semaphore::signal() {
this->value++;
if (this->value > 0) { this->blocked = false; }
wakeup();
}
void Semaphore::signal_all() {
this->value++;
if (this->value > 0) { this->blocked = false; }
while (!waitingPCB.empty()) {
wakeup();
}
}
void Semaphore::block(const shared_ptr<PCB>& pcb) {
pcb->change_state(WAITING);
cout << "Uspiono proces: " << pcb->name << '\n';
this->waitingPCB.push(pcb);
}
void Semaphore::wakeup() {
if (!this->waitingPCB.empty()) {
if (this->waitingPCB.front() != nullptr) {
cout << "Obudzono proces: " << waitingPCB.front()->name << '\n';
this->waitingPCB.front()->change_state(RUNNING);
this->waitingPCB.pop();
}
}
}
const bool& Semaphore::is_blocked() const {
return blocked;
}
const int& Semaphore::get_value() const {
return this->value;
}
void Semaphore::set_value(const int& val) {
this->value = val;
}
void Semaphore::show_value() const {
cout << "Aktualna wartosc zmiennej semaforowej: " << get_value() << endl;
}