Home > Mobile >  is there a way to share a function from the main thread with a web worker?
is there a way to share a function from the main thread with a web worker?

Time:02-06

I see that there is a DedicatedWorkerGlobalScope and SharedWorkerGlobalScope in the mdn docs, but no examples on how to use it.

I am wondering is it possible to pass a function from the main thread to the worker? A function that involves things that aren't available in the worker's world.. For example something simple like:

f = (msg) => { console.log(`hello from main thread! worker thread says: ${msg}`); };

And then the worker calling that would make it so that logging to the browser happens from the worker thread. Is something like this possible to do with those global scope apis?

CodePudding user response:

Is there a way to share a function from the main thread with a web worker?

No. The only data that can be shared is binary: buffers. Functions cannot even be transferred or structurally cloned to send them to a worker, the only way to send code is as a string.

I see that there is a DedicatedWorkerGlobalScope and SharedWorkerGlobalScope in the mdn docs, but no examples on how to use it.

There's plenty of examples, look into the pages of all the listed methods!

Is something like this possible to do with those global scope apis?

I think you are confused what "global scope" and "API" mean here. This is not an API to create global scopes or anything, it's just the documentation of which global variables and methods are available in the global scope to code executing in a dedicated or shared web worker. They're essentially the worker equivalents of the Window interface.

CodePudding user response:

You can't pass along a function to a web-worker, only buffers and basic types like strings.

If you trust your function and it is not a closure you can stringify the function, pass it to the web-worker, and create the function in the web-worker:

You main JavaScript:

const f1 = (msg) => { console.log(`hello from main thread! worker thread says: ${msg}`); };
const f1String = f1.toString();

Pass f1String to the web-worker. In web-worker:

let f2;
eval('f2 ='   f1String);
let msg = 'Hi there';
f2(); // 'hello from main thread! worker thread says: Hi there'

UPDATE 1 on closure based on Bergi's comment.

  • Related