Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rayon #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Expand Up @@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rayon = "1.8"
48 changes: 29 additions & 19 deletions index.js
Expand Up @@ -9,10 +9,10 @@ const { WASI } = require("wasi");
const { argv, env } = require("node:process");
const { join } = require("node:path");

const wasi = new WASI({ version: "preview1", args: argv, env });

const file = readFile(join(__dirname, "wasi-threads.wasm"));

const wasi = new WASI({ version: "preview1", args: argv, env });

if (isMainThread) {
(async () => {
const wasm = await WebAssembly.compile(await file);
Expand All @@ -31,23 +31,33 @@ if (isMainThread) {
wasi.start(instance);
})();
} else {
parentPort.on("message", async (start_arg) => {
const wasm = await WebAssembly.compile(await file);
const { memory } = workerData;
const instance = await WebAssembly.instantiate(wasm, {
...wasi.getImportObject(),
wasi: {
"thread-spawn": (arg) => {
const worker = new Worker(__filename, { workerData: { memory } });
worker.postMessage(arg);
const handler = async (start_arg) => {
try {
const wasm = await WebAssembly.compile(await file);
const { memory } = workerData;
const instance = await WebAssembly.instantiate(wasm, {
...wasi.getImportObject(),
wasi: {
"thread-spawn": (arg) => {
const worker = new Worker(__filename, { workerData: { memory } });
worker.postMessage(arg);
},
},
},
env: { memory },
});
// thread id and start_arg
instance.exports.wasi_thread_start(1, start_arg);
process.exit(0);
});
env: { memory },
});
// thread id and start_arg
instance.exports.wasi_thread_start(1, start_arg);
parentPort.removeListener("message", handler);
} catch (e) {
if (e.code.includes("ERR_WASI_NOT_STARTED")) {
// NOP
return;
}
throw e;
} finally {
process.exit(0);
}
};
parentPort.addListener("message", handler);
}

//
16 changes: 9 additions & 7 deletions src/main.rs
@@ -1,11 +1,13 @@
use std::thread;
use rayon::prelude::*;

fn sum_of_squares(input: &[i32]) -> i32 {
input
.par_iter() // <-- just change that!
.map(|&i| i * i)
.sum()
}

fn main() {
let mut x = 10;
thread::scope(|s| {
s.spawn(|| {
x += 20;
});
});
let x = sum_of_squares(&[10, 20, 30, 40]);
println!("{x}");
}
Binary file modified wasi-threads.wasm
Binary file not shown.