Expand description
§wasmworker
Parallelize tasks on WebAssembly without SharedArrayBuffer.
See the README for full documentation including bundler setup and FAQ.
§Quick start
Add to your Cargo.toml:
[dependencies]
wasmworker = { version = "0.4", features = ["macros"] }§Defining worker functions
use serde::{Deserialize, Serialize};
use wasmworker::{webworker, webworker_fn};
/// An arbitrary type that is (de)serializable.
#[derive(Serialize, Deserialize)]
pub struct VecType(Vec<u8>);
/// A sort function on a custom type.
#[webworker_fn]
pub fn sort_vec(mut v: VecType) -> VecType {
v.0.sort();
v
}
// Obtain a type-safe handle to the function:
let ww_sort = webworker!(sort_vec);§Running tasks
let worker = WebWorker::new(None).await.expect("Couldn't create worker");
let sorted = worker.run(webworker!(sort_vec), &VecType(vec![3, 1, 2])).await;
assert_eq!(sorted.0, vec![1, 2, 3]);let worker_pool = worker_pool().await;
let sorted = worker_pool.run(webworker!(sort_vec), &VecType(vec![3, 1, 2])).await;
assert_eq!(sorted.0, vec![1, 2, 3]);§Configuring the worker pool
let mut options = WorkerPoolOptions::new();
options.num_workers = Some(2); // Default is navigator.hardwareConcurrency
init_worker_pool(options).await.expect("Worker pool already initialized");Re-exports§
pub use pool::WorkerPoolOptions;pub use pool::WebWorkerPool;
Modules§
Macros§
- webworker
- This macro safely instantiates a
WebWorkerFninstance to be passed to acrate::WebWorker. It ensures that the function is exposed via the#[webworker_fn]procedural macro. - webworker_
channel - This macro safely instantiates a
WebWorkerChannelFninstance to be passed to acrate::WebWorker. It ensures that the function is exposed via the#[webworker_channel_fn]procedural macro.
Structs§
- Already
Initialized - Error returned when
init_worker_poolis called after the worker pool has already been initialized. - Channel
- A bidirectional communication channel between the main thread and a WebWorker.
- Channel
Task - A handle to a running channel task on a WebWorker.
- WebWorker
- This struct represents a single web worker instance.
It can be created using
WebWorker::neworWebWorker::with_path. When an instance of this type is dropped, it also terminates the corresponding web worker.
Functions§
- has_
worker_ pool - This function checks if the worker pool has been initialized.
- init_
optimized_ worker_ pool - JavaScript-accessible function to initialize an optimized worker pool globally. This creates a worker pool that precompiles and shares WASM across all workers for optimal bandwidth usage.
- init_
worker_ pool - This function can be called before the first use of the global worker pool to configure it.
It takes a
WorkerPoolOptionsconfiguration object. Note that this function is async. - worker_
pool - This function accesses the default worker pool.
If
init_worker_poolhas not been manually called, this function will initialize the worker pool prior to returning it.