Created
August 11, 2014 02:24
-
-
Save bpceee/e77d32664b97864c9db7 to your computer and use it in GitHub Desktop.
pessimistic lock in nodejs
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
function partial(f) { | |
var args = Array.prototype.slice.call(arguments, 1) | |
return function() { | |
var remainingArgs = Array.prototype.slice.call(arguments) | |
return f.apply(null, args.concat(remainingArgs)) | |
} | |
} | |
var options = { | |
db: { | |
safe: true | |
} | |
} | |
var mongoose = require('mongoose'); | |
mongoose.connect('mongodb://localhost/test', options); | |
var ThingSchema = new mongoose.Schema({ | |
count: Number, | |
}); | |
var Thing = mongoose.model('Thing', ThingSchema); | |
var lock = true; | |
var id = "53e5fec1bcb589c92f6f38dd"; | |
var doAdd = function(id){ | |
if(lock == false) | |
{ | |
setTimeout(partial(arguments.callee, id), 0); | |
} | |
else{ | |
lock = false; | |
Thing.findById(id, function(err, thing){ | |
console.log(thing.count) | |
thing.count++; | |
thing.save(function(){ | |
lock = true; | |
}); | |
}); | |
} | |
}; | |
doAdd(id); | |
doAdd(id); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment