> Hi, I try to implement Peterson algorithm in java. That is very easy.
> Here you are:
[quoted text clipped - 29 lines]
>
> please help.
> ppp napisal(a):
>> Hi, I try to implement Peterson algorithm in java. That is very easy.
[quoted text clipped - 33 lines]
> i know the answer:
> yes - that should I do.
However, there are some subtle issues with the memory model that you
need to consider. See the thread "Peterson's Algorithm in java,
sequencial instruction execution ?" in this group.
Patricia
ppp - 04 Dec 2006 15:46 GMT
ok. Peterson algorithm is simple. I have found another - Lamport
algorithm.
http://en.wikipedia.org/wiki/Lamport's_bakery_algorithm
I want to implement this in my program for N threads. I'm wondering how
to do it.
can i "cut" this algorithm to 2 methods (like in Peterson) enter/leawe
Region? (in this way: lines 3-14 enterRegion(int i); line 16:
leaveRegion(int i)?
ppp - 04 Dec 2006 23:30 GMT
i can, if someone will search for the soluthion - here it is.
public class Lamport {
private static int N = 1; // howMenyThreads
private static int[] enter = new int[N];
private static int[] number = new int[N];
public void enterRegion(int i) {
enter[i] = 1;
number[i] = 1 + maximum(number);
enter[i] = 0;
for (int j = 0; j < N; j++) {
while (enter[j] != 0) {
// wait until thread j receives its number
}
while ((number[j] != 0) && ((number[j]<number[i]) ||
(number[j]==number[i] && j<i) )) {
// wait until threads with smaller numbers or with the same
// number, but with higher priority, finish their work
}
}
}
public void leaveRegion(int i) {
number[i] = 0;
}
private int maximum(int[] table) {
int result=table[0];
for (int i=0;i<table.length;i++) {
if (result<table[i])
result = table[i];
}
return result;
}
}
ppp napisal(a):
> ok. Peterson algorithm is simple. I have found another - Lamport
> algorithm.
[quoted text clipped - 7 lines]
> Region? (in this way: lines 3-14 enterRegion(int i); line 16:
> leaveRegion(int i)?