Skip to content

wasm_thread leaks thread stacks #27

@BGR360

Description

@BGR360

When running wasm-bindgen workers that use shared memory, you need to call <wasm module>.__wbindgen_thread_destroy() from JavaScript in order to deallocate the stack for the thread, otherwise it leaks. This is a problem for applications that want to use wasm_thread to spawn many threads over a period of time rather than make a static thread pool.

This is mentioned briefly in the wasm-bindgen parallel raytracing example (emphasis my own):

There is no standard notion of a "thread". For example the standard library has no viable route to implement the std::thread module. As a consequence there is no concept of thread exit and TLS destructors will never run. We do expose a helper, __wbindgen_thread_destroy, that deallocates the thread stack and TLS. If you invoke it, it must be the last function you invoke from the Wasm module for a given thread.

Some more details on this can be found in the wasm-bindgen source code.

A practical example is shown here:

  // Clean up thread resources. Depending on what you're doing with the thread, this might
  // not be what you want. (For example, if the thread spawned some javascript tasks
  // and exited, this is going to cancel those tasks.) But if you're using threads in the
  // usual native way (where you spin one up to do some work until it finisheds) then
  // you'll want to clean up the thread's resources.

  // Free memory (stack, thread-locals) held (in the wasm linear memory) by the thread.
  init.__wbindgen_thread_destroy();
  // Tell the browser to stop the thread.
  close();

I think actually that the call to close() should come before the call to __wbindgen_thread_destroy(), that way it's guaranteed that there are no outstanding JavaScript tasks that may execute code in the Wasm module before/during the call to __wbindgen_thread_destroy(). Or maybe that's not possible?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions