你可以在 Web Workers 之间共享 WebAssembly 内存吗? [英] Can you share WebAssembly memory between Web Workers?

查看:356
本文介绍了你可以在 Web Workers 之间共享 WebAssembly 内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过使用 postMessage(如 SharedArrayBuffer)在 2 个工作人员之间共享 WebAssembly.memory?如果答案是肯定的,怎么办?

Is it possible to share WebAssembly.memory between 2 workers by using postMessage, something like SharedArrayBuffer? And if the answer is yes, how?

推荐答案

您可以通过 JavaScript API 创建一个 WebAssembly 共享内存实例:

You can create a WebAssembly shared memory instance via the JavaScript API:

const memory = new WebAssembly.Memory({
  initial: 80,
  maximum: 80,
  shared: true
});

然后,您可以通过 postMessage 将此内存实例发送给 Web Worker:

You can then send this memory instance to a Web Worker via postMessage:

const worker = new Worker("worker.js");
worker.postMessage({ memory });

文件 worker.js 然后可以使用这个共享内存实例创建一个 WebAssembly 模块,允许它在不同线程中的模块实例之间共享.

The file worker.js can then create a WebAssembly module using this shared memory instance, allowing it to be shared across module instance in different threads.

有关更完整的示例,请参阅此博客文章:

For a more complete example, see this blog post:

使用多线程 WebAssembly 实现更快的分形

这篇关于你可以在 Web Workers 之间共享 WebAssembly 内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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