Wednesday, September 25, 2019

multithreading - Simulating context switches in JavaScript?




I've been working on implementing a pretty complex system in JavaScript that needs to simulate, among other things, multithreaded processes. In a real multithreaded process (such as a kernel thread) it's possible to switch between threads by context-switching. This works because you can store the current process's program counter and registers to a temporary structure, restore the program counter and registers for some other process, and then resume where you left off in the previous process.



I'm curious whether it's possible to have something similar to this in JavaScript. I currently know no way of doing this and so have been designing the system using cooperative multitasking. In particular, any "function" that I want to run in the multithreading simulator is split up into an array of functions. To execute the "function", I iterate across the array of functions, executing each in order while maintaining a "program counter" of which function to execute next. This allows me to simulate a context switch by calling one of the functions in the array, waiting for the function to return, then switching to some other array of functions that need to be executed.



My current approach works, but it's difficult to write code in this system. Each function has to indicate specifically when it can be interrupted, and because the functions in the array are all separate the logic for communicating data between different parts of the function is complicated. I was hoping to get something closer to preemptive multitasking working instead.



My question is: is it possible to run an arbitrary JavaScript function in a way where it can be suspended and resumed by an external source?


Answer



Check StratifiedJS out


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...