12

Is there any way for me to share a variable between two web workers? (Web workers are basically threads in Javascript)

In languages like c# you have:

public static string message = "";
static void Main()
{
 message = "asdf";
 new Thread(mythread).Run();
}
public static void mythread()
{
 Console.WriteLine(message); //outputs "asdf"
}

I know thats a bad example, but in my Javascript application, I have a thread doing heavy computations that can be spread across multiple threads [since I have a big chunk of data in the form of an array. All the elements of the array are independent of each other. In other words, my worker threads don't have to care about locking or anything like that]

I've found the only way to "share" a variable between two threads would be to create a Getter/setter [via prototyping] and then use postMessage/onmessage... although this seems really inefficient [especially with objects, which I have to use JSON for AFAIK]

LocalStorage/Database has been taken out of the HTML5 specification because it could result in deadlocks, so that isn't an option [sadly]...

The other possibility I have found was to use PHP to actually have a getVariable.php and setVariable.php pages, which use localstorage to store ints/strings... once again, Objects [which includes arrays/null] have to be converted to JSON... and then later, JSON.parse()'d.

As far as I know, Javascript worker threads are totally isolated from the main page thread [which is why Javascript worker threads can't access DOM elements

Although postMessage works, it is slow.

Mmmh mmh
  • 5,334
  • 3
  • 21
  • 29
Warty
  • 7,237
  • 1
  • 31
  • 49
  • You can use sharedArrayBuffer which will be cloned when send to postMessage. Here is a article about it [link](https://50linesofco.de/post/2017-02-06-javascript-in-parallel-web-workers-transferables-and-sharedarraybuffer) – yousef khalil Mar 24 '20 at 14:42

4 Answers4

17

Web workers are deliberately shared-nothing -- everything in a worker is completely hidden from other workers and from pages in the browser. If there were any way to share non-"atomic" values between workers, the semantics of those values would be nearly impossible to use with predictable results. Now, one could introduce locks as a way to use such values, to a certain extent -- you acquire the lock, examine and maybe modify the value, then release the lock -- but locks are very tricky to use, and since the usual failure mode is deadlock you would be able to "brick" the browser pretty easily. That's no good for developers or users (especially when you consider that the web environment is so amenable to experimentation by non-programmers who've never even heard of threads, locks, or message-passing), so the alternative is no state shared between workers or pages in the browser. You can pass messages (which one can think of as being serialized "over the wire" to the worker, which then creates its own copy of the original value based on the serialized information) without having to address any of these problems.

Really, message-passing is the right way to support parallelism without letting the concurrency problems get completely out of control. Orchestrate your message handoffs properly and you should have every bit as much power as if you could share state. You really don't want the alternative you think you want.

Jeff Walden
  • 7,008
  • 2
  • 38
  • 55
  • If there were any way to share non-"atomic" values between workers, the semantics of those values would be impossible to use with predictable results.<-- Absolutely wrong in every way. – Tony Aug 03 '12 at 00:46
  • 1
    Lamport's bakery algorithm. Dijkstra guarded command logic. It all is specifically for non-deterministic predictability. – Tony Sep 04 '12 at 20:01
  • 1
    Fine, "nearly impossible", then. It remains true that sharing non-simple data is very easy to get wrong, and for that reason isn't something you can do with web workers. – Jeff Walden Sep 05 '12 at 23:17
  • What your really trying to say is that the experience and domain knowledge of most programmers in that space would result in nearly unpredictable results. In programming, all power comes with responsibility; or patterns to mitigate the risk. :p – QueueHammer Aug 19 '13 at 22:06
  • 3
    Sure. Given the utter garbage that pollutes much of the code on the web, I think I'm justified in my skepticism toward web developers' abilities to use any sort of thing correctly. – Jeff Walden Sep 03 '13 at 22:48
  • Actually you could share data using Channel Messaging API. – Warlock Jun 16 '15 at 18:40
6

There are two options to share data between dedicated workers:

1. Shared Workers

The SharedWorker interface represents a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iframes or even workers.

Spawning a Shared Worker in a Dedicated Worker

2. Channel Messaging API

The Channel Messaging API allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a SharedWorker, or two workers) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end.

How to call shared worker from the web worker?

Community
  • 1
  • 1
Warlock
  • 7,321
  • 10
  • 55
  • 75
  • Shared workers are workers that can be linked in a network of messages, instead of the simple messaging tree of dedicated workers. However the basic principle of workers holds true : you cannot share anything between workers, only pass messages. – solendil Jul 09 '15 at 09:49
  • 1
    But the compatibility :/ https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker#Browser_compatibility – Luckylooke Dec 16 '15 at 14:03
5

No, but you can send messages to web workers which can be arrays, objects, numbers, strings, booleans, and ImageData or any combination of these. Web workers can send messages back too.

Eli Grey
  • 35,104
  • 14
  • 75
  • 93
2

I recently read about (but have not used), shared workers. According to Share the work! Opera comes with SharedWorker support, support is only in the newest browsers (Opera 10.6, Chrome 5, Safari 5).

Kevin Hakanson
  • 41,386
  • 23
  • 126
  • 155