Skip to content

Instantly share code, notes, and snippets.

@T-Oner

T-Oner/alloc_pid.java

Last active Mar 31, 2020
Embed
What would you like to do?
public class Main {
static int last = -1;
static int pids;
static int usedPid = 0;
public static void main(String[] args) {
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
// 释放 pid 为 3 的程序
pids = pids & ~(1 << 3);
usedPid -= 1;
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
pids = pids & ~(1 << 6);
usedPid -= 1;
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
System.out.println(allocPid());
}
private static int allocPid() {
if (usedPid == 10) {
throw new RuntimeException("No pid resources!");
}
int pid = last;
do {
pid += 1;
if (pid >= 10) {
pid = 0;
}
} while ((1 << pid) == ((1 << pid) & pids));
pids = pids | (1 << pid);
last = pid;
usedPid++;
return pid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.