问题描述
是否可以从Web Worker调用共享工作者?
Is it possible to call a Shared Worker from the Web Worker?
请您举个例子。
在我的情况下,我有一些网络工作者,我需要在他们之间共享单身人士服务。
In my case I have a few web workers and I need to share a singleton service between them.
推荐答案
SharedWorker
构造函数目前在 WorkerGlobalScope
中不可用,因此您将无法像在一个iframe或窗口。
The SharedWorker
constructor is not currently available within the WorkerGlobalScope
, so you will not be able to construct an instance like you would in an iframe or window.
你可以做的是,创建一个,并使用它在worker和sharedWorker之间进行通信。虽然这样做可以消除对实际 SharedWorker
的需求,因为您也可以使用单个 Worker
。
What you can do is, create a MessageChannel for each of your workers, and use it to communicate between the worker and sharedWorker. Though doing this would negate the need for an actual SharedWorker
, since you could just as well use a single Worker
instead.
示例:
var numWorkers = 4;
var sharedWorker = new Worker("worker-shared.js");
for(var i = 0; i < numWorkers; i++) {
var dedicatedWorker = new Worker("worker-dedicated.js");
var channel = new MessageChannel();
dedicatedWorker.postMessage({sharedWorkerPort: channel.port1}, [channel.port1]);
sharedWorker.postMessage({workerPort: channel.port2}, [channel.port2]);
}
这篇关于如何从Web工作者调用共享工作者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!