Is it possible for two separate tasks operating concurrently to access and modify the same array simultaneously?

Imagine you have an array being altered by one asynchronous process and then another asynchronous process reading from the same array. The modifications and reads happen synchronously. So, the big question here is: can the read process somehow access the array while it's being modified by the write process?

Based on my experience, it seems unlikely that the read process would be able to access the array while synchronous operations are happening. When a thread is busy with synchronous tasks, all resources it operates on (including the array) are blocked. Is this behavior a direct result of JavaScript being single-threaded, or is it explicitly specified in the language specifications?

Answer №1

Is it possible for the read process to access the array while it is being modified by the write process?

In JavaScript, since it is single-threaded, there is no way for the read process to access the data concurrently as the write process modifies it. The only option to achieve this in JS is by using shared resources between different scripts. For instance, on the web, you can utilize WebWorkers with SharedArrayBuffers or in Nodejs, certain databases allow for concurrent mutations.

Does this restriction stem from the fact that JavaScript is single-threaded, or is it explicitly stated in the specifications?

The specifications indeed define threads known as Agents:

8.3 Agents

An agent encompasses a collection of ECMAScript execution contexts, an execution context stack, a running execution context, a set of named job queues, an Agent Record, and an executing thread. Apart from the executing thread, all components of an agent are exclusively assigned to that agent.

This implies that all code runs on the same thread (job queue) and variables are only accessible within one thread (execution context). To share memory among different agents (threads), a SharedArrayBuffer must be used, requiring distinct Agents such as Webworkers.

Answer №2

To tackle this situation, I suggest creating 3 separate arrays.

 let kingArray = [];
 let arrayForProcess1 = [];
 let arrayForProcess2 = [];

 someProcessOneExecution().then(response => {
    if (kingArray.length === 0) {
       arrayForProcess1 = response;
    } else {
       doSomethingWithResponse(response);
    }
 });

 someProcessTwoExecution().then(response => {
    if (kingArray.length === 0) {
       arrayForProcess2 = response;
    } else {
       doSomethingWithResponse(response);
    }
 });

 function doSomethingWithResponse() {
    // perform an action here..
 }

While not a direct answer to your query, it's worth noting that the javascript event loop or call stack will handle these promises sequentially due to JS being single-threaded. As they resolve, either process1 or process2 will be executed. Monitoring them manually (as shown above) may not be the most efficient method.

Alternate Approach

In such cases, I would recommend chaining the promises together and awaiting their resolution individually before updating the respective arrays.

From my perspective (a personal opinion), attempting simultaneous updates on the same array may result in execution issues; reevaluating the strategy might be necessary in such scenarios.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Different types of arrays suitable for the useState hook

I have a scenario where I am utilizing setState to assign an array of objects. Here is the code snippet: const [friendList, setFriendList] = useState<any>(); const _onCompleted = (data: any) => { let DATA = data.me.friends.map( (item ...

Retrieving Parts of a URL in AngularJS

Is there a way to extract all parts of a URL after "/"? For example: http://myadress.com/#/example/url/here/param1 Result: ['example', 'url', 'here']. Currently, $routeParams only returns an object with route parameters lik ...

display the text from the template after selecting it (including both the text-field and value-field)

I'm currently utilizing BootstrapVue. In my b-form-select component, I display the name (as the text field) in the selection within my child.vue and emit the age (as the value field) to my parent.vue. This functionality is functioning as intended. H ...

Using Node.js to generate PDF documents and send them directly to the response stream

I am currently utilizing PDFKit, a PDF generation library for Node.js, which can be found at pdfkit.org. My goal is to send a PDF as a response to a client. # Save the PDF file to the disk doc.write('output.pdf'); The code provided above saves ...

What is the best way to eliminate a white border that appears only on my ThreeJS website when viewed on a mobile device?

I initially suspected a potential issue with resizing the window, so I created a JavaScript function to handle it. However, that did not resolve the problem. Any other ideas on how to troubleshoot this? // If the user resizes the window, update camera a ...

Transferring $routeParams from AngularJS to Spring MVC controller

Here is the code snippet from my AngularJs controller: .when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"}) app.controller('conMFs',function($scope,$routeParams){ $scope.otherId = $routeParams.topicId; }); And this is my implementati ...

Tips for inserting line breaks within a <p> element in a contentEditable division

When I press enter or shift+enter on my contentEditable div, the new line is shown as a textNode within the div. However, I prefer the new line to be inside a p element. Seeking a straightforward solution Utilizing React Js, I store the content of the co ...

nvim-typescript incorrectly flags non-existent type errors

I am experimenting with using neovim and have set up a minimal configuration as follows: call plug#begin() Plug 'mhartington/nvim-typescript', {'do': './install.sh'} Plug 'leafgarland/typescript-vim' Plug 'He ...

Obtaining undefined values for req and resolvedUrl in GetServerSideProps function

In my project, I am currently using next.js version ""next": "^12.1.4"" and node version ""@types/node": "^14.14.6". I have created a function called getServerSideProps with parameters req and resolvedUrl. When the ...

Leveraging pre-rendered HTML in Vue.js components for both parent and child elements

Currently, I am rendering all the HTML server-side and attempting to use Vue to set this HTML as the $el for two components. According to the lifecycle diagram, this should be possible. There is a parent Vue instance (which binds to #main) that contains a ...

Tips for preventing the parent from being dragged along with its child

In my current React project, I have implemented a navigation bar where users can drag and rearrange items within the bar successfully. Now, I am working on rendering the navigation tree recursively so that inner navigations can also be draggable without c ...

The Cordova InAppBrowser plugin has not been properly set up

After running cordova plugin list, I noticed that the InAppBrowser plugin is listed. However, when I try to run my code on an android device, I receive this message in the console via Chrome Remote Debugger: Native: InAppBrowser is not installed or you ar ...

Utilizing Node.js and Express to create router instances integrated with a database functionality

My understanding from researching the Express documentation is that when declaring an express.Router(), it creates a single instance of a router where you can assign a routing path and execute logic. The concept of a router being like a mini-app for specif ...

Having trouble importing a TypeScript module from the global node_modules directory

I have a library folder located in the global node modules directory with a file named index.ts inside the library/src folder //inside index.ts export * from './components/button.component'; Now I am trying to import this into my angular-cli ap ...

Is there a way to convert HTML into a structured DOM tree while considering its original source location?

I am currently developing a user script that is designed to operate on https://example.net. This script executes fetch requests for HTML documents from https://example.com, with the intention of parsing them into HTML DOM trees. The challenge I face arise ...

Is there a way to properly handle the loading of all images within a specific jQuery selection?

After running the code below, it is executed for each item in the selection: $('.someElement img').load( function() { // Do something }); Consequently, if .someElement has 5 images, it triggers 5 separate times. How can I set up an event so ...

submitting image data from HTML5 canvas using an HTML post request

I am having issues sending canvas data to the server side as an image. Despite making an HTTP post request, I am unable to retrieve the data on the server side. $_POST remains empty, even though I can see the image data when console logging the object on t ...

What is the best way to ensure my <h5> element fits perfectly inside its parent div vertically?

Currently facing an issue with finding a solution to my problem. The challenge involves having a header tag nested within multiple divs. Below is the structure: <div class="card"> <div class="layout-left"> <div class="card-header"> ...

Having trouble with the checkbox functionality. Attempting to dynamically toggle gridlines in a flot chart

First, I'll share the code and then provide an explanation. Below is a snippet of the relevant HTML: <div id='gridButton'> <form> <input type="checkbox" id="gridCheck" value="showGrid">Show Grid </form ...

Row in Internet Explorer 7

I have a function that reveals hidden rows in a table, which works perfectly in all tested browsers except for IE7. The function is written using Prototype.js. function showInactives(){ var row_list = $$('tr.inactive'); var ck =$('inactive_ ...