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