Read the original article:NAPI Multithreaded Crash Issue
NAPI Multithreaded Crash Issue
Problem Description
Fatal: ecma_vm cannot run in multi-thread! thread:3096 currentThread:3550.
This error indicates that the JavaScript virtual machine (VM) is being accessed from the wrong thread. Thread 3096 is the one that originally created the JS environment, but thread 3550 is trying to access it. Since the JS VM is not designed to work across threads, this causes a crash.
Background Knowledge
The Ark JavaScript runtime enforces strict thread ownership of the VM. Each VM instance must only be accessed from the thread that created it. Accessing the VM from another thread violates this rule and triggers a crash through the engine’s built-in multi-thread detection mechanism.
Troubleshooting Process
- Analyzed crash logs and identified that the crash is triggered when invoking
napi_call_function. - Observed that the function was being called from a thread different from the one that created the JS environment.
- Confirmed that Ark runtime rejects such access by design, leading to a fatal error.
Analysis Conclusion
The crash is caused by incorrect NAPI usage across multiple threads. Specifically, attempts to access the JS VM from a thread that does not own the environment trigger the runtime detection mechanism and terminate the process.
Solution
The JS engine includes a multi-thread detection mechanism to safeguard the runtime. To avoid crashes:
- Ensure that
napi_valueis initialized tonullptrwhen necessary. - Verify that NAPI APIs are used correctly and only in the correct thread context.
- If multi-threaded interaction is required, design the native module so that JS operations are dispatched back to the owning thread instead of calling them directly from worker threads.
Verification Result
After correcting the NAPI API usage and ensuring that JS calls are executed on the owning thread, the crash no longer occurs. Tests confirm stable runtime behavior without multi-thread violations.
Top comments (0)