gpt4 book ai didi

java - 用 Java 实现 Peterson 锁

转载 作者:行者123 更新时间:2023-12-02 09:46:42 24 4
gpt4 key购买 nike

我正在尝试实现 Peterson's algorithm在 Java 中,暂时创建了以下内容

public class Peterson {
private volatile boolean[] flag = new boolean[2];
private volatile int victim;

public void lock(int id)
{
//System.out.println(id);
int i = id;
int j = 1 - id;
flag[i] = true;
victim = i;
while (flag[j] && victim == i) {};
}

public void unlock(int id)
{
flag[id] = false;
}
}

我得到了以下代码来测试锁...

class Counter {
private int value;

public Counter(int c) {
value = c;
}

public int get()
{
return value;
}

public int getAndIncrement() {
return value++;
}
}


class Thread1 implements Runnable {
private Counter c;
private int id;
private List<Integer> values;
private Peterson lock;

public Thread1(Counter c, int id, List<Integer> values, Peterson l) {
this.c = c;
this.id = id;
this.values = values;
this.lock = l;
}

public void run() {

while (true)
{
lock.lock(id);
try {
try {

if (c.get() > 20000)
return;

int n = c.getAndIncrement();
values.add(n);
} catch (Exception e) {
e.printStackTrace();
}
}
finally {
lock.unlock(id);
}
}
}
}

public class Tmp {

public static void main(String[] args) throws IOException {

Counter c = new Counter(1);
Thread[] t = new Thread[2];
List<Integer> values = new ArrayList<Integer>();
Peterson l = new Peterson();

for (int i = 0; i < t.length; ++i) {
t[i] = new Thread(new Thread1(c, i, values, l));
t[i].start();
}

System.out.println(values.size());
}
}

虽然我希望 System.out.println(values.size()); 打印 20000 但它在每次运行时打印不同的数字。为什么是这样?我做错了什么?

最佳答案

解锁时不会创建内存屏障,以保证之前发生

添加一个 volatile boolean barr并在unlock中写入true,并将lock中的while更改为while (barr && flag[j] &&victim == i) {};

这样你就不用等待你创建的线程了

for (int i = 0; i < t.length; ++i)  {
t[i] = new Thread(new Thread1(c, i, values, l));
t[i].start();
}

for (int i = 0; i < t.length; ++i) {
try{
t[i].join();
}catch(InterruptedException e){
Thread.currentThread().interrupt();//don't expect it but good practice to handle anyway
}
}

关于java - 用 Java 实现 Peterson 锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7167549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com