diff --git a/packages/wasi-threads/src/thread-manager.ts b/packages/wasi-threads/src/thread-manager.ts index f720c9c2..c422579d 100644 --- a/packages/wasi-threads/src/thread-manager.ts +++ b/packages/wasi-threads/src/thread-manager.ts @@ -54,11 +54,18 @@ export interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { const WASI_THREADS_MAX_TID = 0x1FFFFFFF export function checkSharedWasmMemory (wasmMemory?: WebAssembly.Memory | null): void { - if (wasmMemory ? !isSharedArrayBuffer(wasmMemory.buffer) : (typeof SharedArrayBuffer === 'undefined')) { - throw new Error( - 'Multithread features require shared wasm memory. ' + - 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking' - ) + if (wasmMemory) { + if (!isSharedArrayBuffer(wasmMemory.buffer)) { + throw new Error( + 'Multithread features require shared wasm memory. ' + + 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' + + 'then create WebAssembly.Memory with `shared: true` option' + ) + } + } else { + if (typeof SharedArrayBuffer === 'undefined') { + throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!') + } } } diff --git a/packages/wasi-threads/src/wasi-threads.ts b/packages/wasi-threads/src/wasi-threads.ts index b71243fb..89650026 100644 --- a/packages/wasi-threads/src/wasi-threads.ts +++ b/packages/wasi-threads/src/wasi-threads.ts @@ -132,9 +132,24 @@ export class WASIThreads { } const threadSpawn = (startArg: number, errorOrTid?: number): number => { - checkSharedWasmMemory(this.wasmMemory) - + const EAGAIN = 6 const isNewABI = errorOrTid !== undefined + + try { + checkSharedWasmMemory(this.wasmMemory) + } catch (err) { + this.PThread?.printErr(err.stack) + if (isNewABI) { + const struct = new Int32Array(this.wasmMemory.buffer, errorOrTid!, 2) + Atomics.store(struct, 0, 1) + Atomics.store(struct, 1, EAGAIN) + Atomics.notify(struct, 1) + return 1 + } else { + return -EAGAIN + } + } + if (!isNewABI) { const malloc = this.wasmInstance.exports.malloc as Function errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : malloc(8) @@ -211,8 +226,6 @@ export class WASIThreads { } } } catch (e) { - const EAGAIN = 6 - Atomics.store(struct, 0, 1) Atomics.store(struct, 1, EAGAIN) Atomics.notify(struct, 1)