Last active
October 23, 2018 07:08
-
-
Save ukyo/eed0e7beff684a14c32806eae780700e to your computer and use it in GitHub Desktop.
WebAssembly Shared Memory example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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