judge: optimize lock (#715)

This commit is contained in:
Yang Gao authored and GitHub committed 2024-01-21 17:26:22 +08:00
1 parent d23db46d0b
commit b231c423b5
1 file changed
+11 -6
+11 -6
View File
@@ -1,6 +1,6 @@
import path from 'path'; import path from 'path';
import { parse } from 'shell-quote'; import { parse } from 'shell-quote';
import { fs, sleep } from '@hydrooj/utils'; import { fs } from '@hydrooj/utils';
import { FormatError } from './error'; import { FormatError } from './error';
const EMPTY_STR = /^[ \r\n\t]*$/i; const EMPTY_STR = /^[ \r\n\t]*$/i;
@@ -8,16 +8,21 @@ const EMPTY_STR = /^[ \r\n\t]*$/i;
export const cmd = parse; export const cmd = parse;
export namespace Lock { export namespace Lock {
const data = {}; const queue: Record<string, Array<(res?: any) => void>> = {};
export async function acquire(key: string) { export async function acquire(key: string) {
// eslint-disable-next-line no-await-in-loop if (!queue[key]) {
while (data[key]) await sleep(100); queue[key] = [];
data[key] = true; } else {
await new Promise((resolve) => {
queue[key].push(resolve);
});
}
} }
export function release(key: string) { export function release(key: string) {
data[key] = false; if (!queue[key].length) delete queue[key];
else queue[key].shift()();
} }
} }