#threading #mt #pool #webassembly #thread #thread-pool #github

nightly wasm-mt-pool

A thread pool library based on wasm-mt

2 releases

0.1.1 Mar 15, 2021
0.1.0 May 25, 2020

#556 in WebAssembly

34 downloads per month
Used in wasm-mt-pool-test

MIT/Apache

67KB
953 lines

wasm-mt-pool

Docs | GitHub | Crate

crates MIT licensed CI

A thread pool library based on wasm-mt (github | crate).

Examples

You can run all the following apps in browser!

  • pool_exec - How to use wasm_mt_pool. [ live | source ]
  • http - A multithreaded server based on wasm_mt_pool. [ live | source ]
  • pool_arraybuffers - Demo of using ThreadPool::new_with_arraybuffers(). [ live | source ]

Getting started

Requirements:

Cargo.toml:

wasm-mt-pool = "0.1"
serde = { version = "1.0", features = ["derive"] }
serde_closure = "0.2"

Usage

#![feature(async_closure)]

use wasm_mt_pool::prelude::*;
use wasm_mt::utils::{console_ln, sleep};

let size = 2;
let pkg_js = "./pkg/pool_exec.js"; // path to `wasm-bindgen`'s JS binding
let pool = ThreadPool::new(size, pkg_js).and_init().await.unwrap();

let num = 4;

console_ln!("a) 💦 pool_exec! {} closures:", num);
for _ in 0..num {
    pool_exec!(pool, move || {
        console_ln!("a) closure: done.");
        Ok(JsValue::NULL)
    });
}

console_ln!("b) 💦 pool_exec! {} async closures:", num);
for _ in 0..num {
    pool_exec!(pool, async move || {
        sleep(1000).await;
        console_ln!("b) async closure: done.");
        Ok(JsValue::NULL)
    });
}

let cb = move |result| {
    console_ln!("callback: result: {:?}", result);
};

console_ln!("c) 💦 pool_exec! {} closures with callback:", num);
for _ in 0..num {
    pool_exec!(pool, move || {
        console_ln!("c) closure: done.");
        Ok(JsValue::from("C"))
    }, cb);
}

console_ln!("d) 💦 pool_exec! {} async closures with callback:", num);
for _ in 0..num {
    pool_exec!(pool, async move || {
        sleep(1000).await;
        console_ln!("d) async closure: done.");
        Ok(JsValue::from("D"))
    }, cb);
}

sleep(6_000).await; // Do sleep long enough to ensure all jobs are completed.
assert_eq!(pool.count_pending_jobs(), 0);

Dependencies

~7–10MB
~191K SLoC