Skip to content

Commit

Permalink
fix: fix race condition where WASM-Module is instantiated twice; and …
Browse files Browse the repository at this point in the history
…rebuild

fix race condition where WASM-Module is instantiated twice
(phoboslab/jsmpeg@d368010); and rebuild
(phoboslab/jsmpeg@c56be4e)
  • Loading branch information
cycjimmy committed Mar 15, 2022
1 parent b04df7e commit 490801a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
38 changes: 34 additions & 4 deletions src/lib/wasm-module.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,53 @@ export default class WASM {
constructor() {
this.stackSize = 5 * 1024 * 1024; // emscripten default
this.pageSize = 64 * 1024; // wasm page size
this.onInitCallback = null;
this.onInitCallbacks = [];
this.ready = false;
this.loadingFromFileStarted = false;
this.loadingFromBufferStarted = false;
}

write(buffer) {
this.loadFromBuffer(buffer, this.onInitCallback);
this.loadFromBuffer(buffer);
}

loadFromFile(url, callback) {
if (callback) {
this.onInitCallbacks.push(callback);
}

// Make sure this WASM Module is only instantiated once. If loadFromFile()
// was already called, bail out here. On instantiation all pending
// onInitCallbacks will be called.
if (this.loadingFromFileStarted) {
return;
}
this.loadingFromFileStarted = true;

this.onInitCallback = callback;
const ajax = new AjaxSource(url, {});
ajax.connect(this);
ajax.start();
}

loadFromBuffer(buffer, callback) {
if (callback) {
this.onInitCallbacks.push(callback);
}

// Make sure this WASM Module is only instantiated once. If loadFromBuffer()
// was already called, bail out here. On instantiation all pending
// onInitCallbacks will be called.
if (this.loadingFromBufferStarted) {
return;
}
this.loadingFromBufferStarted = true;

this.moduleInfo = this.readDylinkSection(buffer);
if (!this.moduleInfo) {
this.callback && this.callback(null);
for (let i = 0; i < this.onInitCallbacks.length; i++) {
this.onInitCallbacks[i](null);
}
return;
}

Expand All @@ -47,7 +75,9 @@ export default class WASM {
}
this.createHeapViews();
this.ready = true;
callback && callback(this);
for (let i = 0; i < this.onInitCallbacks.length; i++) {
this.onInitCallbacks[i](this);
}
});
}

Expand Down
Loading

0 comments on commit 490801a

Please sign in to comment.