Compare commits

..

4 Commits

Author SHA1 Message Date
5ccbb2ef1c Simplified selectColumnSizeHeuristic 2021-02-25 00:49:41 -07:00
da1405f262 Update Dockerfile 2021-02-25 00:38:11 -07:00
2f8801bae6 Worker threads message 2021-02-25 00:37:54 -07:00
67ec0d5430 Update all imports to .js for esm support, use threads.js
threads.js has better support for modules - no need to give a
project-relative path to the worker file, which complicated the build.

Add rudimentary thread pooling w/ execution timeout.
2021-02-25 00:34:34 -07:00

View File

@ -34,15 +34,7 @@ function initialize() {
} }
initialize(); initialize();
/** function withTimeout<T>(promise: Promise<T>, ms: number, cb: () => Error) {
* Awaits a promise with a timeout.
*
* @param promise the promise to await
* @param ms the timeout in milliseconds
* @param cb a callback to call when the timeout is reached. The promise is
* rejected with whatever gets returned here.
*/
function withTimeout<T>(promise: Promise<T>, ms: number, cb: () => any) {
let timeout: NodeJS.Timeout; let timeout: NodeJS.Timeout;
return new Promise<T>((resolve, reject) => { return new Promise<T>((resolve, reject) => {
timeout = setTimeout(() => { timeout = setTimeout(() => {
@ -57,27 +49,31 @@ export async function generate(
regionHeight: number, regionHeight: number,
clues: number clues: number
): Promise<Sudoku> { ): Promise<Sudoku> {
const proxy = available.pop(); const proxy = available.shift();
if (!proxy) { if (!proxy) {
throw new Error("No workers available right now. Please try again."); throw new Error("No workers available right now. Please try again.");
} }
const puzzle = await withTimeout<number[]>( try {
proxy.generate(regionWidth, regionHeight, clues), const puzzle: number[] = await withTimeout(
TIMEOUT, proxy.generate(regionWidth, regionHeight, clues),
() => { TIMEOUT,
Thread.terminate(proxy); () => {
getWorker().then((worker) => available.push(worker)); Thread.terminate(proxy);
return new Error("Timed out. Try reducing the number of clues."); getWorker().then((worker) => available.push(worker));
} return new Error("Timed out. Try reducing the number of clues.");
); }
);
available.push(proxy); available.unshift(proxy);
prettyPrint(regionWidth, regionHeight, puzzle); prettyPrint(regionWidth, regionHeight, puzzle);
return { return {
regionWidth, regionWidth,
regionHeight, regionHeight,
size: (regionWidth * regionHeight) ** 2, size: (regionWidth * regionHeight) ** 2,
cells: puzzle, cells: puzzle,
}; };
} catch (err) {
throw err;
}
} }