chen chen -4 years ago 69
jQuery Question

Why does not this callback function cause race condition?

I don't understand why the following code does not cause potential race condition. It looks like

count
and
totalBytes
are variables that can be accessed by multiple callback functions and I felt
count--
and
totalBytes += stats.size
might cause racing because you can't guarantee the orders of the callback functions passed to
fs.stat()
(as it's an IO operation).

var fs = require('fs');

var count = 0,
totalBytes = 0;

function calculateByteSize() {
fs.readdir(".", function (err, filenames) {
var i;
count = filenames.length;

for (i = 0; i < filenames.length; i++) {
fs.stat("./" + filenames[i], function (err, stats) {
totalBytes += stats.size;
count--;
if (count === 0) {
console.log(totalBytes);
}
});
}
});
}

calculateByteSize();

Answer Source

Javascript has only one thread, therefore only one callback could be modifying count at a time. Order of callbacks, however, is not guaranteed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download