Created
July 14, 2012 14:48
-
-
Save eugeneware/3111702 to your computer and use it in GitHub Desktop.
Atomic Update Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Currently the output is something like this (indeterminate each time you run it):