soon this i will explain
1
For this total 5 versions are there, the
final & perfect solution is the below one by ramu.
Main()
2
{
3
4
// to denote which thread will enter next
5
int favouredthread = 1;
6
7
// flags to indicate if each thread is in
8
// queue to enter its critical section
9
boolean thread1wantstoenter = false;
10
boolean thread2wantstoenter = false;
11
12
startThreads();
13
}
14
15
Thread1()
16
{
17
do {
18
19
thread1wantstoenter = true;
20
21
// entry section
22
// wait until thread2 wants to enter
23
// its critical section
24
while (thread2wantstoenter == true) {
25
26
// if 2nd thread is more favored
27
if (favaouredthread == 2) {
28
29
// gives access to other thread
30
thread1wantstoenter = false;
31
32
// wait until this thread is favored
33
while (favouredthread == 2)
34
;
35
36
thread1wantstoenter = true;
37
}
38
}
39
40
// critical section
41
42
// favor the 2nd thread
43
favouredthread = 2;
44
45
// exit section
46
// indicate thread1 has completed
47
// its critical section
48
thread1wantstoenter = false;
49
50
// remainder section
51
52
} while (completed == false)
53
}
54
55
Thread2()
56
{
57
58
do {
59
60
thread2wantstoenter = true;
61
62
// entry section
63
// wait until thread1 wants to enter
64
// its critical section
65
while (thread1wantstoenter == true) {
66
67
// if 1st thread is more favored
68
if (favaouredthread == 1) {
69
70
// gives access to other thread
71
thread2wantstoenter = false;
72
73
// wait until this thread is favored
74
while (favouredthread == 1)
75
;
76
77
thread2wantstoenter = true;
78
}
79
}
80
81
// critical section
82
83
// favour the 1st thread
84
favouredthread = 1;
85
86
// exit section
87
// indicate thread2 has completed
88
// its critical section
89
thread2wantstoenter = false;
90
91
// remainder section
92
93
} while (completed == false)
94
}
This version guarantees a complete solution to the critical solution problem.
కామెంట్లు లేవు:
కామెంట్ను పోస్ట్ చేయండి