简体   繁体   English

如何在 Web Workers 之间有效共享 state?

[英]How can I share state effectively between Web Workers?

I'm looking at porting a game to HTML5, but I'm running into some problems.我正在考虑将游戏移植到 HTML5,但我遇到了一些问题。

The game uses multithreading quite a bit, with rendering running on the main thread and scripts running on worker threads.该游戏大量使用多线程,渲染在主线程上运行,脚本在工作线程上运行。 Multiple scripts can (and frequently do) run concurrently.多个脚本可以(并且经常)同时运行。 It's got a fair amount of global data that any script can access, mostly to read from but occasionally to write to as well.它有相当数量的全局数据,任何脚本都可以访问,主要用于读取,但偶尔也用于写入。 Mechanisms are in place to ensure that thread safety is not a problem.机制已到位以确保线程安全不是问题。

It looks like HTML 5 Web Workers can be used to set up multithreading, but getting the global data to work will be a big problem, as there doesn't appear to be any easy way to share data between workers.看起来像 HTML 5 Web Worker 可以用来设置多线程,但是让全局数据工作将是一个大问题,因为似乎没有任何简单的方法可以在 worker 之间共享数据。 I could theoretically put all the global data in a shared worker and have each script worker send it messages to get and set data, but access is common enough that the message-passing overhead would completely destroy performance, especially since a simple read would be far more expensive than a write, and potentially require some sort of CPS implementation just to make it work.理论上我可以将所有全局数据放在一个共享的工作程序中,让每个脚本工作程序向它发送消息以获取和设置数据,但访问非常普遍,以至于消息传递开销会完全破坏性能,特别是因为简单的读取会很远比写入更昂贵,并且可能需要某种 CPS 实现才能使其工作。

Is there any good way to port an architecture like this to HTML5 and JavaScript?有没有什么好的方法可以将这样的架构移植到 HTML5 和 JavaScript?

I wonder if you couldn't either use something like an in memory database like sqlite (or if more is needed, a full on postgres database or something), or alternately something like websockets, for implementing something like this.我想知道您是否不能使用类似 memory 数据库(如 sqlite)之类的东西(或者如果需要更多,完整的 postgres 数据库或其他东西),或者像 websockets 之类的东西来实现这样的东西。 I haven't done much concurrency in js so I am not sure what the drawbacks would be.我没有在js中做太多并发,所以我不确定会有什么缺点。 Of the two I sort of like the websockets idea better.在这两者中,我更喜欢 websockets 的想法。 Another option that occurs to me is to use some kind of a message queue, like rabbitmq or kafka.我想到的另一个选择是使用某种消息队列,例如 rabbitmq 或 kafka。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM