Skip to content

Instantly share code, notes, and snippets.

@ukyo
Last active October 23, 2018 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ukyo/eed0e7beff684a14c32806eae780700e to your computer and use it in GitHub Desktop.
Save ukyo/eed0e7beff684a14c32806eae780700e to your computer and use it in GitHub Desktop.
WebAssembly Shared Memory example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
>
<meta
http-equiv="X-UA-Compatible"
content="ie=edge"
>
<title>threads</title>
</head>
<body>
<button id="btn">Say Hello!</button>
<script src="main.js"></script>
</body>
</html>
const worker = new Worker("worker.js");
const memory = new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
worker.postMessage(memory);
btn.onclick = () => {
const states = new Int32Array(memory.buffer);
Atomics.wake(states, 0, 1);
};
onmessage = async e => {
const module = await new WebAssembly.compileStreaming(fetch("worker.wasm"));
const idx = 0;
const memory = e.data;
const imports = {
env: { memory, idx },
fn: {
wait: () => {
const states = new Int32Array(memory.buffer);
return +(Atomics.wait(states, idx, 0) === "ok");
},
hello: () => {
console.log("hello");
}
}
};
const instance = await WebAssembly.instantiate(module, imports);
};
(module
(import "env" "memory" (memory 1 1 shared))
(import "env" "idx" (global $idx i32))
(import "fn" "hello" (func $hello))
(import "fn" "wait" (func $wait (result i32)))
(func $foo (export "foo")
block $exit
loop $cont
;; get_global $idx i32.const 0 i64.const -1 i32.atomic.wait
call $wait i32.eqz br_if $exit
call $hello
get_global $idx i32.const 0 i32.atomic.store
br $cont
end
end
)
(start $foo)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment