An effective way to implement semaphore locking in a web worker?

为君一笑 提交于 2019-12-12 17:43:12

问题


I have a huge piece of code (compiled with Emscripten) running inside a web worker. The page kicks off a task in the worker with one postMessage, and when the worker is finished, it sends another postMessage back. Great. However, I have a new feature I'd like to add that requires me to pause the worker mid-execution, kick a message back to the browser via postMessage, wait for the user to submit a valid response via postMessage, and then finish execution. However, I can't figure out anything that works. My attempts to have the worker wait in an infinite loop until a control variable is set on arrival of the message fails because the infinite loop prevents the execution of the worker's message handler. I can break out of the worker execution by throwing an exception, but then I have no idea how to resume execution.

Does anyone have any ideas?


回答1:


The way I would go about this would be to have a main "controller" worker running as a shared Web Worker. I would then have that controller spin off other Workers where necessary, taking messages/commands via postMessage.

That way, your shared worker is like your main loop and will keep things running smooth. I would avoid doing any sort of non-asynchronous work in that main loop.




回答2:


In JS, one way to create a interrupt-like mechanism is by using setTimeout(some_function,1). This way, the code some_function execution completes, the other event handlers can be processed if they are in the queue.

This pattern will depend on whether the "huge piece of code" that you mentioned can be split into sequential steps ( or methods). say, if it something like:

step1();
step2();
step3();

So, say during the execution of "step1" method, if you get an 'interrupt' or in other words a "message" event occurs, it can be handled after step finishes execution but before step2 starts.

It all just depends on what exactly is the nature of the problem that is being solved by your piece of code. some more context will be handy.



来源:https://stackoverflow.com/questions/11007322/an-effective-way-to-implement-semaphore-locking-in-a-web-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!