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 next5
int favouredthread = 1;6
7
// flags to indicate if each thread is in8
// queue to enter its critical section9
boolean thread1wantstoenter = false;10
boolean thread2wantstoenter = false;11
12
startThreads();13
}14
15
Thread1()16
{17
do {18
19
thread1wantstoenter = true;20
21
// entry section22
// wait until thread2 wants to enter23
// its critical section24
while (thread2wantstoenter == true) {25
26
// if 2nd thread is more favored27
if (favaouredthread == 2) {28
29
// gives access to other thread30
thread1wantstoenter = false;31
32
// wait until this thread is favored33
while (favouredthread == 2)34
;35
36
thread1wantstoenter = true;37
}38
}39
40
// critical section41
42
// favor the 2nd thread43
favouredthread = 2;44
45
// exit section46
// indicate thread1 has completed47
// its critical section48
thread1wantstoenter = false;49
50
// remainder section51
52
} while (completed == false)53
}54
55
Thread2()56
{57
58
do {59
60
thread2wantstoenter = true;61
62
// entry section63
// wait until thread1 wants to enter64
// its critical section65
while (thread1wantstoenter == true) {66
67
// if 1st thread is more favored68
if (favaouredthread == 1) {69
70
// gives access to other thread71
thread2wantstoenter = false;72
73
// wait until this thread is favored74
while (favouredthread == 1)75
;76
77
thread2wantstoenter = true;78
}79
}80
81
// critical section82
83
// favour the 1st thread84
favouredthread = 1;85
86
// exit section87
// indicate thread2 has completed88
// its critical section89
thread2wantstoenter = false;90
91
// remainder section92
93
} while (completed == false)94
}This version guarantees a complete solution to the critical solution problem.
కామెంట్లు లేవు:
కామెంట్ను పోస్ట్ చేయండి