在 Web-Worker 中同步等待消息 [英] Synchronously Wait for Message in Web-Worker

查看:41
本文介绍了在 Web-Worker 中同步等待消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以同步等待或检查网络工作者中的新消息吗?

Is there some way to synchronously wait for or check for a new message in a web-worker?

我有大量复杂的代码(从 emscripten 编译的 LLVM),我无法围绕回调进行重构.

I have a large complicated body of code (compiled LLVM from emscripten) that I cannot refactor around callbacks.

我需要确保特定行之后的代码在我收到并处理来自 UI 线程的消息之前不会执行.如果我使用 while 循环阻塞,则事件循环永远不会运行,因此我无法接收消息.

I need to make sure that code after a certain line doesn't execute until I receive and handle a message from the UI-thread. If I block with a while-loop, the event-loop never runs so I can't receive messages.

推荐答案

这是我在使用 Pyodide.我想从主线程同步"调用一个函数.

This is an issue that I also ran into while working with Pyodide. I wanted to 'synchronously' call a function from the main thread.

一种解决方案涉及Atomics 和SharedArrayBuffer API.从 web worker 的角度来看,这看起来像下面

One solution involves the Atomics and SharedArrayBuffer APIs. From the perspective of the web worker, this looks like the following

  1. postMessage 主线程
  2. Atomics.wait
  3. 冻结自己
  4. 被主线程解冻
  5. SharedArrayBuffer 读取结果.我们无法以 postMessage 的形式接收结果,因为没有同步方式询问我收到消息了吗".
  1. postMessage the main thread
  2. freeze ourselves with Atomics.wait
  3. get unfrozen by the main thread
  4. read the result from a SharedArrayBuffer. We can't receive the result as a postMessage, because there isn't a synchronous way of asking "did I get a message".

当然,这需要大量额外的代码来处理所有的序列化、数据传递等.

Of course this requires a fair amount of extra code to handle all the serialization, data passing and more.

其中的一个限制是它不能在 Safari 中工作,因为 Safari 没有实现 Atomic 的 API.另一个限制是,要使用这些 API,需要有 COOP/COEP 标头设置.

One limitation of this are that it won't work in Safari, because Safari does not implement the Atomics API. Another limitation is that to use those APIs, one needs to have the COOP/COEP headers set.

还有一个替代解决方案 同步XHR 和 Service Worker,但我还没有研究过这个选项.

There is also an alternative solution with synchronous XHR and a service worker, but I haven't investigated that option.

这篇关于在 Web-Worker 中同步等待消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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