熟悉代码
腾哥给了些任务
通读完judger的核心代码,跟黄学长联系修改完OLE,就开始尝试研究命令行启动的线程模型优化。(因为judger的代码在github上是公开的,so我这里就直接贴腾哥的代码啦)
@author:张腾学长
public class CommandExecutor {
// CPU 池
private final Queue<Integer> cpuPool;
// 线程池
private final CompletionService<CommandExecuteResult> threadPool;
/**
* @Description 提交一个异步任务
**/
public void submit(Command command) {
threadPool.submit(new CommandThread(command, cpuPool));
}
/**
* @Description 获取一个任务的执行结果,顺序任意取决于任务完成顺序
* @return cn.edu.sdu.qd.oj.judger.dto.CommandExecResult
**/
public CommandExecuteResult take() throws InterruptedException, ExecutionException {
return threadPool.take().get();
}
public CommandExecutor() {
// 初始化 cpu 池,从本机配置文件中读取运行的核心都有哪些
cpuPool = new LinkedBlockingDeque<>(CpuConfig.getCpuSet());
// 初始化线程池
threadPool = new ExecutorCompletionService<>(new ThreadPoolExecutor(
cpuPool.size(),
cpuPool.size(),
0,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1024),
new ThreadPoolExecutor.CallerRunsPolicy())
);
log.info("init threadPool {}", cpuPool.size());
}
private static class CommandThread implements Callable<CommandExecuteResult> {
private final Command command;
private final Queue<Integer> cpuPool;
public CommandThread(Command command, Queue<Integer> cpuPool) {
this.command = command;
this.cpuPool = cpuPool;
}
@Override
public CommandExecuteResult call() throws Exception {
log.info("exec {}", command.toString());
Integer coreNo = null;
try {
coreNo = cpuPool.poll();
log.info("cpu consume {}", coreNo);
return command.run(coreNo != null ? coreNo : 0);
} finally {
log.info("cpu release {}", coreNo);
if (coreNo != null) {
cpuPool.offer(coreNo);
}
}
}
}
}
cpupool是cpu核心池,通过读取本机的cpu配置文件获得,是一些离散的数字,所以用双端队列储存,从头取,运行结束放回到队伍尾部。
@author:张腾学长
public class SandboxRunner {
private static final String SANDBOX_PATH = "/usr/bin/sandbox";
public static SandboxResultDTO run(String cwd, Argument... args) throws SystemErrorException {
return run(CpuConfig.getCpuSet().iterator().next(),cwd, args);
}
public static SandboxResultDTO run(int coreNo, String cwd, Argument... args) throws SystemErrorException {
List