Skip to content

Fix emscripten_set_immediate when called from a pthread#27008

Open
sbc100 wants to merge 1 commit into
emscripten-core:mainfrom
sbc100:setimmediate
Open

Fix emscripten_set_immediate when called from a pthread#27008
sbc100 wants to merge 1 commit into
emscripten-core:mainfrom
sbc100:setimmediate

Conversation

@sbc100
Copy link
Copy Markdown
Collaborator

@sbc100 sbc100 commented May 24, 2026

We have special handling for the setimmediate message in the pthreads code. Without this change, emscripten_set_immediate (which uses emSetImmediate under the hood) was using _si as its message ID. This meant that when called from a worker, the message sent to the main thread was not recognized and therefore not forwarded back to the worker, causing the immediate callback to never run.

By unifying both to use setimmediate, we can reuse the existing pthreads forwarding logic.

Also update emSetImmediate to check if it is running in a worker and omit the target origin argument when calling postMessage, as the worker version of postMessage does not support it. This matches the logic already present in the EM_TIMING_SETIMMEDIATE main loop implementation.

Add a pthread variant to test_emscripten_set_immediate to prevent regressions.

@sbc100 sbc100 requested a review from kripken May 24, 2026 05:53
@sbc100 sbc100 force-pushed the setimmediate branch 3 times, most recently from cf27cfa to a602c5e Compare May 24, 2026 17:18
We have special handling for the `setimmediate` message in the pthreads
code to forward it back to the worker. Without this change,
`emscripten_set_immediate` (which uses `emSetImmediate` under the hood)
was using `_si` as its message ID and was not getting forwarded, causing
immediate callbacks to never run in workers.

To fix this while avoiding event listener interference when both
`emscripten_set_immediate` and the `EM_TIMING_SETIMMEDIATE` main loop
are active in the same thread, we use unique message IDs for each
polyfill (`em-setimmediate` and `ml-setimmediate`) and update the
pthreads forwarding logic to support both.

Also update `emSetImmediate` to check if it is running in a worker and
omit the target origin argument when calling `postMessage`, as the worker
version of `postMessage` does not support it. This matches the logic
already present in the `EM_TIMING_SETIMMEDIATE` main loop implementation.

Add a pthread variant to `test_emscripten_set_immediate` to prevent regressions.
@sbc100 sbc100 changed the title Unify emscripten_set_immediate with EM_TIMING_SETIMMEDIATE Fix emscripten_set_immediate when called from a pthread May 24, 2026
@sbc100 sbc100 requested a review from kleisauke May 24, 2026 17:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant