JS & concurrency questions?

Suppose I have simple code;

var counter = 0; var sharedResource = [];//some shared resource function incrementAndModify(){ if(counter == 0) { sharedResource.push(Math.random());//very sensitive data counter++; } } function init(){ incrementAndModify(); doAjaxGetWithCallback(function(){incrementAndModify();}); incrementAndModify(); } 

So the question is: will incrementAndModify () function run atomically or not? I read that JS runs on a single thread and there can be no problems with concurrency. But the question is still open (at least for me).

instead

 doAjaxGetWithCallback(function(){incrementAndModify();}); 

I could write something like:

 doAjaxGetWithCallback(function(){ doSomeCrazyStuffThatDoesNotUseSharedResource(); incrementAndModify(); doSomeOtherCrazyStuffThatDoesNotUseSharedResource(); }); 
+4
source share
3 answers

JavaScript in the browser is single-threaded (excluding web-worker s), so you don't need to worry about concurrency. Essentially, every block of code is atomic, no matter how long. If incrementAndModify() performs some very processor-intensive time operations and an AJAX response, the callback will not be executed until the current incrementAndModify() completes and releases a single thread.

This is also the reason that synchronous AJAX calls are discouraged: an AJAX request may take some time during which other code cannot be executed (the thread of execution is too busy). This forces the GUI to freeze, as no other user events are processed.

see also

By the way:

 doAjaxGetWithCallback(function(){incrementAndModify();}); 

can be written as follows:

 doAjaxGetWithCallback(incrementAndModify); 
+3
source

Do not be afraid that this will only someday be warned.

 // sync example var happened = false; setTimeout(dontDoTwice, 0); setTimeout(dontDoTwice, 0); setTimeout(dontDoTwice, 0); function dontDoTwice() { if (!happened) { alert("ALERT! ALERT! ALERT!"); happened = true; } } 

A bit more complicated example: http://jsfiddle.net/7BZ6H/1/

0
source

Yes, the incrementAndModify() function will always work atomically. This is because of the Run-to-Completion javascript function.

See Why there is no concurrency control in javascript for more details.

0
source

Source: https://habr.com/ru/post/1402681/


All Articles