4 ms·
I had some problems with SpiderMonkey's thread safe mode. If you have your own lock system, and you lock a resource while running JS, SM might do garbage collec
by udp 16y ago
I had some problems with SpiderMonkey's thread safe mode. If you have your own lock system, and you lock a resource while running JS, SM might do garbage collection at any time, for which it has its own lock. This causes deadlock very quickly indeed.
I had to resort to having a pool of JS runtimes from which each thread would borrow a runtime when it wanted to execute code, and return it when it was finished. This got messy quickly when I found out that script objects can't be shared, and I needed to load an individual copy of each script for each runtime.
Furthermore, JS objects weren't able to be shared between threads even when I didn't have separate runtimes, and I needed to (this was actually the recommended approach) write them to a binary format using JS_WriteStructuredClone when one thread was finished with them, and reassemble them with JS_ReadStructuredClone on the other end.
In the end, I gave up trying to do multithreaded Javascript and went for a nice, single threaded event driven model. I don't regret it. Heck, since it's lock-free - and structured clone free - it's probably more scalable!
- bnoordhuis 16y agoI hear you, threading in SM is indeed fraught with dangers. On the off chance that you're going to revisit it, the way to go is to compile with -DJS_THREADSAFE and register a callback with JS_SetGCCallback() that tells the VM when it's safe to run the garbage collector. Actually, the approach I took was to always tell the VM 'no' and invoke JS_GC() manually from time to time. Conceptually easy and performance is mostly amortized. PS: Feel free to contact me if you have follow-up questions, my email is in my profile.