js: Properly manage workers when useWorkers is called twice #626
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Before this change, calling useWorkers twice would allocate new workers but keep old workers around; this resulted in old workers leaking when the new count was larger; when the new count was smaller, we would still maintain the worker count but recreate some workers and leak older ones.
Instead we now only create more workers if more workers are requested, and if the requested count is smaller than current worker count, we ask some existing workers (nicely) to close by sending a dummy message.
Because messages are processed in order, and processing the worker response does not access global workers[], it should be safe to call useWorkers(0) at any point without disrupting already dispatched requests. This also provides a clean way to reclaim all resources used by the workers, including WebAssembly memory.
Fixes #522 (by allowing
useWorkers(1)
/useWorkers(0)
to be used to clean up resources)