Synchronization: onerror events and n++
I'm just reading a bit into JavaScript and came over some code that handle the process of loading images:
var n = 0;
...
for (...) {
...
image[i].onload = function { n++; };
}
Is this piece of code safe or can there be any type of race while acc开发者_JS百科essing the variable n
?
The time at which the ONLOAD event for each image is raised (relatively to each other, if at ever) is generally non-deterministic. Consider issues like browser cache or concurrent downloads, or failed attempts.
However, there is only one JavaScript "execution context" at a time; that is, the final value of n
will reflect the total amount of times that ONLOAD handler is invoked (at that given time). That is, for a given page, all JS is atomic until it finishes (yields to the browser until an event occurs)
"Web Workers" also fit within this event model; there is no traditional "race condition" between threads and variable access. However, any shared (mutable) state between tasks can result in a race-condition, albeit at at higher-levels.
This is pretty safe since most JavaScript is run in a single threaded context. The only caveat is Web Workers but they are designed quite well and can only communicate via JSON messages.
精彩评论