// Path: src/main/java/com/github/mottox/taomp/common/ThreadID.java
// public class ThreadID {
// 
//     private static Map<Long, Integer> threadIDs = new ConcurrentHashMap<>();
// 
//     private static AtomicInteger counter = new AtomicInteger();
// 
//     public static int get() {
//         long id = Thread.currentThread().getId();
//         return threadIDs.computeIfAbsent(id, key -> counter.getAndIncrement());
//     }
// }


import java.util.concurrent.atomic.AtomicBoolean;
import com.github.mottox.taomp.common.ThreadID;
package com.github.mottox.taomp.concurrent.locks;



/**
 * Peterson锁，一种{@link LockOne}和{@link LockTwo}结合起来的无饥饿锁算法。
 * 在TAOMP中将其称为最简洁与最完美的双线程互斥算法，以其发明者名字命名。
 */
public class Peterson implements SimpleLock {

    private AtomicBoolean[] flag = new AtomicBoolean[2];

    private volatile int victim;

    public Peterson() {
        flag[0] = new AtomicBoolean(false);
        flag[1] = new AtomicBoolean(false);
    }

    @Override
    public void lock() {
// Path: src/main/java/com/github/mottox/taomp/common/ThreadID.java
// public class ThreadID {
// 
//     private static Map<Long, Integer> threadIDs = new ConcurrentHashMap<>();
// 
//     private static AtomicInteger counter = new AtomicInteger();
// 
//     public static int get() {
//         long id = Thread.currentThread().getId();
//         return threadIDs.computeIfAbsent(id, key -> counter.getAndIncrement());
//     }
// }


// Path: src/main/java/com/github/mottox/taomp/concurrent/locks/Peterson.java
import java.util.concurrent.atomic.AtomicBoolean;
import com.github.mottox.taomp.common.ThreadID;

package com.github.mottox.taomp.concurrent.locks;



/**
 * Peterson锁，一种{@link LockOne}和{@link LockTwo}结合起来的无饥饿锁算法。
 * 在TAOMP中将其称为最简洁与最完美的双线程互斥算法，以其发明者名字命名。
 */
public class Peterson implements SimpleLock {

    private AtomicBoolean[] flag = new AtomicBoolean[2];

    private volatile int victim;

    public Peterson() {
        flag[0] = new AtomicBoolean(false);
        flag[1] = new AtomicBoolean(false);
    }

    @Override
    public void lock() {
        int i = ThreadID.get();