/ proof-of-concept / toy-instruments
Sign in
proof-of-concept / toy-instruments
toy-instruments / src / sim / run.ts
46 lines · 1.2 KBBlameHistoryRaw
1import type { BeadSystem, Excitation, SimOptions, SimResult } from './types';
3export interface Running {
4 promise: Promise<SimResult>;
5 cancel: () => void;
6}
8// onPartial gets the result so far every few seconds while the run is in progress
9export function runInWorker(
10 sys: BeadSystem,
11 exc: Excitation,
12 opt: SimOptions,
13 gpu: boolean,
14 onProgress: (f: number) => void,
15 onPartial?: (r: SimResult) => void,
16): Running {
17 const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });
18 let reject!: (e: Error) => void;
19 const promise = new Promise<SimResult>((res, rej) => {
20 reject = rej;
21 worker.onmessage = (ev) => {
22 const m = ev.data;
23 if (m.type === 'progress') onProgress(m.fraction);
24 else if (m.type === 'partial') onPartial?.(m.result);
25 else if (m.type === 'done') {
26 worker.terminate();
27 res(m.result);
28 } else {
29 worker.terminate();
30 rej(new Error(m.message));
31 }
32 };
33 worker.onerror = (e) => {
34 worker.terminate();
35 rej(new Error(e.message));
36 };
37 });
38 worker.postMessage({ sys, exc, opt, gpu });
39 return {
40 promise,
41 cancel: () => {
42 worker.terminate();
43 reject(new Error('cancelled'));
44 },
45 };
↑↓ move↵openescclose