-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOS Task ResourceOrdering.cpp
More file actions
75 lines (67 loc) · 1.8 KB
/
OS Task ResourceOrdering.cpp
File metadata and controls
75 lines (67 loc) · 1.8 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
#define PTW32_NO_TIMESPEC
#define _TIMESPEC_DEFINED
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <windows.h>
#include <thread>
using namespace std;
#define NUM 5
sem_t Forks[NUM];
sem_t Once;
void Pick(int PhilNum) {
sem_wait(&Forks[PhilNum % NUM]);
}
void Put(int PhilNum) {
sem_post(&Forks[PhilNum % NUM]);
}
void Think(int PhilNum) {
printf("philosopher %d is Think\n", PhilNum);
return;
}
void Eat(int PhilNum) {
printf("philosopher %d is Eat\n", PhilNum);
return;
}
void* Phil(void* arg) {
int PhilNum;
PhilNum = (unsigned long int) arg;
while (1) {
if (PhilNum < 4) {
Pick(PhilNum);
printf("philosopher %d picks up the fork %d.\n", PhilNum, PhilNum);
Pick(PhilNum + 1);
printf("philosopher %d picks up the fork %d.\n", PhilNum, (PhilNum + 1) % NUM);
}
else {
Pick(PhilNum + 1);
printf("philosopher %d picks up the fork %d.\n", PhilNum, (PhilNum + 1) % NUM);
Pick(PhilNum);
printf("philosopher %d picks up the fork %d.\n", PhilNum, PhilNum);
}
Eat(PhilNum);
Put(PhilNum + 1);
printf("philosopher %d puts down the fork %d.\n", PhilNum, (PhilNum + 1) % NUM);
Put(PhilNum);
printf("philosopher %d puts down the fork %d.\n", PhilNum, PhilNum);
Think(PhilNum);
}
return NULL;
}
int main() {
pthread_t Thrds[NUM];
sem_init(&Once, 0, 1);
for (int i = 0; i < NUM; i++) {
sem_init(&Forks[i], 0, 1);
}
for (unsigned long int i = 0; i < NUM; i++) {
pthread_create(&Thrds[i], NULL, Phil, (void*)i);
}
for (int i = 0; i < NUM; i++) {
pthread_join(Thrds[i], NULL);
}
return 0;
}