How to stop an emscripten worker immediately?

193 views
Skip to first unread message

Ben Wiley

unread,
Oct 26, 2021, 12:44:46 PM10/26/21
to emscripte...@googlegroups.com
I have a program compiled with Emscripten to WebAssembly. Every time I start processing data (which can take awhile) I spin up a worker with emscripten_create_worker. And I give the user an option to cancel. But if the user starts and stops the work repeatedly we can end up with several concurrent workers, despite only the most recent worker being valuable. On mobile platforms I'm able to make the program run out of WASM memory by quickly cycling between start/cancel even though I allow the program to dynamically grow memory.

I tried killing the worker on cancel using emscripten_destroy_worker, but when I profiled my program afterward with Chrome performance tools, I saw that the workers continue to run to completion, in concurrence. In other words it seems like emscripten_destroy_worker isn't doing anything.

Is there a secret to killing a worker that is still running? Do I need to sleep in the middle of execution?

Ben

Jukka Jylänki

unread,
Oct 27, 2021, 2:46:33 AM10/27/21
to emscripte...@googlegroups.com
It is likely that the worker needs to be yielded back to the browser's
event loop in order for the .terminate() command (called by
emscripten_destroy_worker) to apply.

You'll likely need to cooperatively track cancellation state in the
worker, and abort doing the computation if user does cancel in the
middle of execution. Synchronously sleeping will likely not affect the
situation.
> --
> You received this message because you are subscribed to the Google Groups "emscripten-discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to emscripten-disc...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/emscripten-discuss/CAOD6y0jkT9TSG0eiyJQyGa%2Bb%2Bxn3TFrS3WCV6Jvr_gqNxDodNw%40mail.gmail.com.

Ben Wiley

unread,
Oct 27, 2021, 2:09:20 PM10/27/21
to emscripte...@googlegroups.com
For anyone interested, I was able to solve this problem by refactoring my code to run a series of jobs with single responses in a persistent worker rather than one long job with many provisional responses. That way I can check a cancelled variable in the main thread before running each job. Unfortunately this approach has longer total runtime but the tradeoff is acceptable for me.
Reply all
Reply to author
Forward
0 new messages