You are on page 1of 1

Documentation Downloads Community

Home » API Reference » Wasm Workers API

Wasm Workers API


The Wasm Workers API enables C/C++ code to leverage Web Workers and shared
WebAssembly.Memory (SharedArrayBuffer) to build multithreaded programs via a direct web-
like programming API.

Quick Example 

#include <emscripten/wasm_worker.h>
#include <stdio.h>

void run_in_worker()
{
printf("Hello from wasm worker!\n");
}

int main()
{
emscripten_wasm_worker_t worker = emscripten_malloc_wasm_worker(/*stack size: */1024);
emscripten_wasm_worker_post_function_v(worker, run_in_worker);
}

Build the code by passing the Emscripten flag -sWASM_WORKERS at both compile and link steps.
The example code creates a new Worker on the main browser thread, which shares the same
WebAssembly.Module and WebAssembly.Memory object. Then a postMessage() is passed to
the Worker to ask it to execute the function run_in_worker() to print a string.

To explicitly control the memory allocation placement when creating a worker, use the function
emscripten_create_wasm_worker() .

Introduction
In WebAssembly programs, the Memory object that contains the application state can be
shared across multiple Workers. This enables direct, high performance (and if explicit care is
not taken, racy!) access to synchronously share data state between multiple Workers (shared
state multithreading).

Emscripten supports two multithreading APIs to leverage this web feature:

You might also like