The WebAssembly workflow

In order to utilize Wasm modules in separate threads, the Wasm file must be compiled in the main thread and instantiated in a Web Worker. Let's review this process in more detail:

  1. A new Web Worker (we'll refer to it as wasmWorker) is created using the Worker() constructor.
  2. A fetch call is made to retrieve a .wasm file and the arrayBuffer() function is called on the response.
  3. The resolved value of the arrayBuffer() function is passed to the WebAssembly.compile() function.
  4. The WebAssembly.compile() function resolves with a WebAssembly.Module instance, which is included in the body of a message posted to the wasmWorker using the postMessage() function.
  5. Within wasmWorker, the WebAssembly.Module instance from the message body is passed to the WebAssembly.instantiate() function, which resolves with a WebAssembly.Instance.
  6. The WebAssembly.Instance exports object is assigned to a local variable in wasmWorker and is used to call Wasm functions.

To call a function from the wasmWorker Wasm instance, you post a message to the worker thread with any arguments to pass to the Wasm function. Then, wasmWorker executes the function and passes the results back to the main thread. That's the crux of how threads are utilized in the context of Web Workers. Before we move on to the example application, you may need to address a limitation that Google Chrome imposes. Follow the instructions in the Limitations in Google Chrome section to ensure the example application works successfully.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset