Skip to content

Instantly share code, notes, and snippets.

@eugeneware
Created July 14, 2012 14:48
Show Gist options
  • Save eugeneware/3111702 to your computer and use it in GitHub Desktop.
Save eugeneware/3111702 to your computer and use it in GitHub Desktop.
Atomic Update Problem
var stream = require('stream');
var fs = require('fs');
// clear the data file
fs.writeFileSync('data.txt', '0');
// Returns a stream that emits a series of asynchronously generated events
var getStream = function() {
var s = new stream.Stream();
var work = [];
for (var i = 0; i < 10; i++) {
work.push(i);
}
var next = function() {
var val = work.shift();
s.emit('data', val);
if (work.length) {
setTimeout(next, 0);
} else {
s.emit('end');
}
};
setTimeout(next, 0);
return s;
};
var s = getStream();
s.on('data', function(data) {
// Ideally would like this read/write 'increment' update to be atomic
fs.readFile('data.txt', function(err, fileData) {
var val = parseInt(fileData.toString(), 10);
val++;
fs.writeFile('data.txt', val, function(err) {
console.log(val + ' written to file');
});
});
});
// check the final written value in the file
// Ideally the final value written in the file would be 10
s.on('end', function() {
var val = parseInt(fs.readFileSync('data.txt').toString());
console.log('Final value = ' + val);
});
@eugeneware
Copy link
Author

Currently the output is something like this (indeterminate each time you run it):


1 written to file
2 written to file
2 written to file
2 written to file
2 written to file
2 written to file
2 written to file
2 written to file
2 written to file
2 written to file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment