Guide: Shared Memory in JavaScript: Quick Guide

Shared memory is an advanced feature JavaScript, which can use threads (parts of a process executed simultaneously). Means sharing memory don’t bother passing updated data between threads and all threads can access and update the same data in shared memory. Doesn’t that sound nice? Well almost. In this post we will see how to use shared memory in JavaScript and how to decide if this is what you really want to do.

Advantages and Disadvantages of Shared Memory

We use web workers to create threads in JavaScriptThe Web Workers API allows us to create worker threads that can be used run code in the background so that the main thread is free to continue its execution, handle possible UI events, so that the UI does not crash. Worker threads run simultaneously with the main thread and each otherSuch a simultaneous execution of different parts of a task is time-saving. You finish faster, but it also has its own problems. Make sure every thread receives the necessary resources and communicates with each other on time is a task in itself, where an accident can lead to a surprising outcome. Or if one thread changes data and another reads it at the same time, what do you think the other thread will see? The updated or the old data? However, web workers are not that easy to screw upDuring their communication through the use of messages, it is the data they send each other not original but a copy, which means they don’t share the same data. They pass copies of data on to each other when needed. But sharing is caring, and multiple threads may need to look at the same data at the same time and change it. So, Prohibiting sharing is a big no-noThis is where the SharedArrayBuffer object comes into the picture. It will let us share binary data between multiple threads

The SharedArrayBuffer object

Instead of passing the data copies between threads, we can pass copies of the SharedArrayBuffer objectA SharedArrayBuffer object points to the memory where the data is stored So even if the SharedArrayBuffer copies are exchanged between threads, they will remain they will all still refer to the same memory where the original data is stored. So the wires can view and update the data in that same memory

Web workers without shared memory

To see how a web worker works without using shared memory, we want create a worker thread and pass some data to it The index.html file contains the main script in a tag, as shown below: const w = new Worker (‘worker.js’); var n = 9; w.postMessage (n); The worker.js file contains the worker script onmessage = (e) => {console.group (‘[worker]’); console.log (‘Data received from main thread:% i’, e.data); console.groupEnd ();} Using the above code, we get the following output in the console [worker]To receive data from the main thread: 9 You can read my aforementioned post on web workers for the full code explanation of the above snippets. For now, keep in mind that data is sent back and forth between threads using the postMessage () method. The data is received on the other end by the message event handler, as the value of the data property of the event. Now, if we change the data does it appear updated on the receiving end? Let’s see: const w = new Worker (‘worker.js’); var n = 9; w.postMessage (n); n = 1; As expected, the data has not been updated [worker]To receive data from the main thread: 9 Why should it actually be? Her just a clone sent to the worker from the main script

Web workers with shared memory

Now we will use the SharedArrayBuffer object in the same example. We can create a new SharedArrayBuffer instance by with the new keywordThe constructor takes one parameter; a length value in bytes, specifying the size of the buffer. const w = new Worker (‘worker.js’); buff = new SharedArrayBuffer (1); var arr = new Int8Array (buff); / * setting data * / arr[0] = 9; / * send the buffer (copy) to employee * / w.postMessage (buff); Note that a SharedArrayBuffer object represents only a shared memory areaTo view and change the binary data, we must use an appropriate data structure (a TypedArray or a DataView object). In the above index.html file, a new SharedArrayBuffer is created, with a length of only one byte. Then a new Int8Array, a type of TypedArray objects, is used set the data to “9” in the provided byte space onmessage = (e) => {var arr = new Int8Array (e.data); console.group (‘[worker]’); console.log (‘Data received from main thread:% i’, arr[0]); console.groupEnd ();} Int8Array is also used in worker, to view the data in the buffer The expected value appears in the console from the worker thread, which is exactly what we wanted: [worker]To receive data from the main thread: 9 Now let’s update the data in the main thread to see if the change is reflected in the employee. const w = new Worker (‘worker.js’), buff = new SharedArrayBuffer (1); var arr = new Int8Array (buff); / * setting data * / arr[0] = 9; / * send the buffer (copy) to employee * / w.postMessage (buff); / * change the data * / arr[0] = 1; And, as you can see below, the update reflects in the employee [worker]To receive data from the main thread: 1 But so does the code should work the other way around: when the value in the employee initially changes, it also needs to be updated when it is printed from the main thread. In this case, our code looks like this: onmessage = (e) => {var arr = new Int8Array (e.data); console.group (‘[worker]’); console.log (‘Data received from main thread:% i’, arr[0]); console.groupEnd (); / * changing the data * / arr[0] = 7; / * posts in main thread * / postMessage (”);} The data is changed in the employee and a empty message is posted to the main thread signaling that the data in the buffer has changed and is ready for output from the main thread. const w = new Worker (‘worker.js’), buff = new SharedArrayBuffer (1); var arr = new Int8Array (buff); / * setting data * / arr[0] = 9; / * send the buffer (copy) to employee * / w.postMessage (buff); / * change the data * / arr[0] = 1; / * print data after employee changes it * / w.onmessage = (e) => {console.group (‘[main]’); console.log (‘Updated data received from worker thread:% i’, arr[0]); console.groupEnd ();} And this works too! The data in the buffer is the same as the data in the employee. [worker]To receive data from the main thread: 1[main]Receive updated data from worker thread: 7 The value will be updated in both casesBoth the main and worker threads view and modify the same data.

Final words

As I mentioned before, I am using shared memory in JavaScript is not without its drawbacksHer up developers to ensure that the the order of execution happens as predicted and no two threads racing to get the same data because no one knows who will take the trophy. If you’re more interested in shared memory, check out the Atomics object documentation. The Atomics object can help you with some of the hardships, by reducing the unpredictable nature of reading / writing from shared memory.

Shared Memory in JavaScript: Quick Guide: benefits

Faq

Final note

I hope you like the guide Shared Memory in JavaScript: Quick Guide. In case if you have any query regards this article you may ask us. Also, please share your love by sharing this article with your friends. For our visitors: If you have any queries regards the Shared Memory in JavaScript: Quick Guide, then please ask us through the comment section below or directly contact us. Education: This guide or tutorial is just for educational purposes. Misinformation: If you want to correct any misinformation about the guide “Shared Memory in JavaScript: Quick Guide”, then kindly contact us. Want to add an alternate method: If anyone wants to add more methods to the guide Shared Memory in JavaScript: Quick Guide, then kindly contact us. Our Contact: Kindly use our contact page regards any help. You may also use our social and accounts by following us on Whatsapp, Facebook, and Twitter for your questions. We always love to help you. We answer your questions within 24-48 hours (Weekend off). Channel: If you want the latest software updates and discussion about any software in your pocket, then here is our Telegram channel.

Shared Memory in JavaScript  Quick Guide 2021  2022  - 35Shared Memory in JavaScript  Quick Guide 2021  2022  - 78Shared Memory in JavaScript  Quick Guide 2021  2022  - 37Shared Memory in JavaScript  Quick Guide 2021  2022  - 58