Clone in a terminal:
Commit 6ce3ae3
Johan Mattsson - 2026-07-10T22:35:05+00:00
6ce3ae3a5b97d326d2495c0250c41b28bd312cc2johan.mattsson.m@gmail.com

Clean up code and identify problems

Changed files (5)

Diff

diff --git a/examples/threads/src/lib.rs b/examples/threads/src/lib.rsindex 3fbd702..5878af8 100644--- a/examples/threads/src/lib.rs+++ b/examples/threads/src/lib.rs@@ -14,16 +14,11 @@ extern "C" { }  mod main_component;-mod pool;+mod thread;  #[wasm_bindgen(start)] pub fn init() {-    log!("Starting");-     std::panic::set_hook(Box::new(console_error_panic_hook::hook));     console_error_panic_hook::set_once();--    log!("Init callbacks");     init_callbacks();-    log!("Init complete"); }diff --git a/examples/threads/src/main_component.rs b/examples/threads/src/main_component.rsindex 596271c..d2d99a7 100644--- a/examples/threads/src/main_component.rs+++ b/examples/threads/src/main_component.rs@@ -28,7 +28,6 @@ impl Component for Main {         };          let mut component = handle.lock().unwrap();-        component.test = !component.test;         component.render(&element);     } }@@ -42,14 +41,25 @@ impl Main { fn start_background_thread(id: &str) {     let component_id = id.to_string(); -    c   rate::thread::spawn(move || {+    crate::thread::spawn(move || {         loop {+            let Some(handle) = Main::get_component(&component_id) else {+                error!("Main component not found:", &component_id);+                break;+            };++            let mut component = handle.lock().unwrap();+            component.test = !component.test;+             Main::post_ui_thread_update(component_id.as_str());             std::thread::sleep(Duration::from_millis(1000));              // this a background thread, so:             // try_inner_html("#test", "<b>INNER_HTML</b>");             // will not update the DOM. Only the UI thread can do that.+            //+            // Run post_ui_thread_update to schedule a UI thread update+            // using the Component::update method.         }     }); }diff --git a/examples/threads/src/thread.rs b/examples/threads/src/thread.rsindex f703b3b..aaf14f6 100644--- a/examples/threads/src/thread.rs+++ b/examples/threads/src/thread.rs@@ -15,9 +15,9 @@ struct Work { fn spawn_worker() -> Result<Worker, JsValue> {     let worker = Worker::new("./worker.js")?; -    // With a worker spun up send it the module/memory so it can start-    // instantiating the Wasm module. Later it might receive further-    // messages about code to run on the Wasm module.+    // A worker spun up send it the module and memory so it can start+    // instantiating the Wasm module.+     let array = js_sys::Array::new();     array.push(&wasm_bindgen::module());     array.push(&wasm_bindgen::memory());@@ -72,7 +72,7 @@ pub fn spawn(f: impl FnOnce() + Send + 'static) -> Result<(), JsValue> {  /// Entry point invoked by `worker.js` #[wasm_bindgen]-pub fn child_entry_point(ptr: u32) -> Result<(), JsValue> {+pub fn init_thread_runner(ptr: u32) -> Result<(), JsValue> {     let ptr = unsafe { Box::from_raw(ptr as *mut Work) };     let global = js_sys::global().unchecked_into::<DedicatedWorkerGlobalScope>();     (ptr.func)();diff --git a/examples/threads/static/index.js b/examples/threads/static/index.jsindex 6ecf9b8..4848f9c 100644--- a/examples/threads/static/index.js+++ b/examples/threads/static/index.js@@ -1,19 +1,28 @@ function loadWasm() {-  if (typeof SharedArrayBuffer !== 'function') {-    console.error('this browser does not have SharedArrayBuffer support enabled' + '\n\n' + msg);-    return-  }-  // Test for bulk memory operations with passive data segments-  //  (module (memory 1) (data passive ""))-  const buf = new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,-    0x05, 0x03, 0x01, 0x00, 0x01, 0x0b, 0x03, 0x01, 0x01, 0x00]);-  if (!WebAssembly.validate(buf)) {-    console.error('This browser does not support passive Wasm memory, Background threads will not work' + '\n\n' + msg);-    return-  }+    if (typeof SharedArrayBuffer !== "function") {+        console.error(+            "this browser does not have SharedArrayBuffer support enabled" ++                "\n\n" ++                msg,+        );+        return;+    }+    // Test for bulk memory operations with passive data segments+    //  (module (memory 1) (data passive ""))+    const buf = new Uint8Array([+        0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x05, 0x03, 0x01, 0x00,+        0x01, 0x0b, 0x03, 0x01, 0x01, 0x00,+    ]);+    if (!WebAssembly.validate(buf)) {+        console.error(+            "This browser does not support passive Wasm memory, Background threads will not work" ++                "\n\n" ++                msg,+        );+        return;+    } -  wasm_bindgen()-    .catch(console.error);+    wasm_bindgen().catch(console.error); }  loadWasm();diff --git a/examples/threads/static/worker.js b/examples/threads/static/worker.jsindex 26d40c6..d162ce4 100644--- a/examples/threads/static/worker.js+++ b/examples/threads/static/worker.js@@ -1,5 +1,5 @@ // synchronously, using the browser, import out shim JS scripts-importScripts('raytrace_parallel.js');+importScripts("raytrace_parallel.js");  // Wait for the main thread to send us the shared module/memory. Once we've got // it, initialize it all with the `wasm_bindgen` global we imported via@@ -7,19 +7,19 @@ importScripts('raytrace_parallel.js'); // // After our first message all subsequent messages are an entry point to run, // so we just do that.-self.onmessage = event => {-  let initialised = wasm_bindgen(...event.data).catch(err => {-    // Propagate to main `onerror`:-    setTimeout(() => {-      throw err;+self.onmessage = (event) => {+    let initialised = wasm_bindgen(...event.data).catch((err) => {+        // Propagate to main `onerror`:+        setTimeout(() => {+            throw err;+        });+        // Rethrow to keep promise rejected and prevent execution of further commands:+        throw err;     });-    // Rethrow to keep promise rejected and prevent execution of further commands:-    throw err;-  }); -  self.onmessage = async event => {-    // This will queue further commands up until the module is fully initialised:-    await initialised;-    wasm_bindgen.child_entry_point(event.data);-  };+    self.onmessage = async (event) => {+        // This will queue further commands up until the module is fully initialised:+        await initialised;+        wasm_bindgen.init_thread_runner(event.data);+    }; };

Contact

Email: johan.mattsson.m@gmail.com
Mastodon: typo.social/@birdfont
GitHub: johanmattssonm
LinkedIn: johan-mattsson-2ab324112