我试图修改著名的"Dekker算法",因此您可以同时将其用于三个进程。这是我的代码:
package DekkersAlgorithm;
class DekkerAlg {
/* Iterations done by each Thread */
static final int iterations = 2000000;
/* Shared variable */
static volatile int sharedInteger = 0;
/* P Thread for critical section */
static volatile boolean wantp = false;
/* Q Thread for critical section */
static volatile boolean wantq = false;
/* Z Thread for critical section */
static volatile boolean wantz = false;
/* Thread turn */
static volatile int turn = 1;
class P extends Thread {
public void run() {
for (int i=0; i<iterations; ++i) {
/* No critical section */
wantp = true;
while (wantq || wantz) {
if (turn == 2) {
wantp = false;
while (turn == 2)
Thread.yield();
wantp = true;
}
}
/* Critical section */
++sharedInteger;
/* End critical section */
turn = 2;
wantp = false;
}
}
}
class Q extends Thread {
public void run() {
for (int i=0; i<iterations; ++i) {
/* No critical section */
wantq = true;
while (wantp || wantz) {
if (turn == 1) {
wantq = false;
while (turn == 1)
Thread.yield();
wantq = true;
}
}
/* Critical section */
--sharedInteger;
/* End critical section */
turn = 1;
wantq = false;
}
}
}
class Z extends Thread {
public void run() {
for (int i=0; i<iterations; ++i) {
/* No critical section */
wantz = true;
while (wantp || wantq) {
if (turn == 3) {
wantz = false;
while (turn == 3)
Thread.yield();
wantz = true;
}
}
/* Critical section */
++sharedInteger;
/* End critical section */
turn = 3;
wantz = false;
}
}
}
DekkerAlg() {
Thread p = new P();
Thread q = new Q();
Thread z = new Z();
p.start();
q.start();
z.start();
try {
p.join();
q.join();
z.join();
System.out.println("The value of the sharedInteger is " + sharedInteger);
System.out.println("It should be different from 0.");
}
catch (InterruptedException e) {}
}
public static void main(String[] args) {
new DekkerAlg();
}
}
它在低迭代中运行良好,但当我将此变量设置为500(+)时,程序有时无法完成。我认为livelock
发生在最后两个Threads
之间,但我需要一条关于如何解决它的线索
你能帮我吗?
我认为您没有正确地扩展turn
。在Dekker中,这意味着如果双方都想,谁可以进入他们的CS;这里的意思似乎是如果其他人想进入他们的CS,谁必须等待。对于两个过程,它们是直接对立的;对于3,没有那么多。
一种方法是有一个进程列表,指定若CS存在竞争,谁必须等待谁。这样,如果P&Q想要进入,而Z刚刚退出,Z会被移到列表的末尾,所以你可以在P&问:(如果你可以用原子的方式来表示这个"列表",这是可行的,因为只有6种不同的模式可以表示,那就更好了!)