问题
I have a situation where I am making several (say four) ajax calls (using AngularJS http get, if that matters) and I want each call to callback and increment a counter, so I can know when all (four) of the threads have completed.
My concern is that since JavaScript does not have anything comparable to Java's "synchronized" or "volatile" keywords, that it would be possible for multiple concurrent threads to collide while incrementing a counter, thereby missing some increments.
In other words, two threads come at the same time, and both read the counter, getting the same value (for example 100). Then both threads increment that counter (to 101) and store the new value, and behold, we missed a count (101 instead of 102)!
I know that JavaScript is supposed to be single threaded, but there are exceptions.
Is this situation possible in the browser, and if so, is there any way to guard against it?
回答1:
No, it is not possible (no collision will occur). Each AJAX call response can be considered a message on the JavaScript message queue. The JavaScript runtime processes each message on the queue to completion before processing the next. In other words, it calls the callback for the event and runs the full callback function (and all the functions it calls, and so on) to completion before moving onto the next message in the queue. Therefore, no two messages (e.g., AJAX responses) will be processed in parallel.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop
Also, I've worked in JavaScript for many years and can guarantee this is how it works.
回答2:
like you mentioned, since javascript is single threaded, I do not think such a scenraio would happen, the only way js becomes multi threaded is when you use webworkers, but even they do not share the same variables( they clone the attribute js objects you pass, i am assuming here), so there should be any case of read/write overlap
EDIT
on second thought, say there is function onCounterIncreament
which would do a bunch of operation when counter increments, if you do not call it immediately after you increamenting counter, but use $watch
or something timeout fn to check for change in counter, there is a good possiblity you might miss a change.
来源:https://stackoverflow.com/questions/27884186/is-it-possible-for-a-concurrent-read-write-read-write-collision-in-javascript-in