在网络工作者中实现信号量锁定的有效方法? [英] An effective way to implement semaphore locking in a web worker?

查看:15
本文介绍了在网络工作者中实现信号量锁定的有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大段代码(用 Emscripten 编译)在 web worker 中运行.该页面使用一个 postMessage 启动 worker 中的一项任务,当 worker 完成时,它会发送另一个 postMessage.伟大的.但是,我想添加一个新功能,它要求我在执行过程中暂停工作线程,通过 postMessage 将消息踢回浏览器,等待用户通过 postMessage 提交有效响应,然后完成执行.但是,我想不出任何有效的方法.我试图让工作人员在无限循环中等待直到在消息到达时设置控制变量失败,因为无限循环阻止了工作人员的消息处理程序的执行.我可以通过抛出异常来中断工作程序执行,但是我不知道如何恢复执行.

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.

有人有什么想法吗?

推荐答案

在 JS 中,创建类似中断的机制的一种方法是使用 setTimeout(some_function,1).这样,代码 some_function 执行完毕,其他事件处理程序如果在队列中就可以处理了.

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();

所以,假设在step1"方法的执行过程中,如果你得到一个中断"或者换句话说一个消息"事件发生,它可以在 step 完成执行之后但在 step2 开始之前处理.

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.

这篇关于在网络工作者中实现信号量锁定的有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆