我正在努力克服互斥的逻辑;我在这里检查钥匙是否被带走,如果没有,我们接受它并在完成时释放它;但是你可以帮我解决一下如何检查密钥,直到它可用为止?
rdb.setnx(lockkey, 'taken', function (err, lockvalue) {
if (err) {
console.error(err);
} else if (lockvalue == 1) {
// You have the lock; process it
//Release the key when you are done:
rdb.del(lockkey);
} else if (lockvalue == 0) {
// Key is taken by someone else; so how can I have a loop to check until key is available to take?
}
});
感谢您的帮助: - )
更新:
非常感谢Adeneco的回答;我一直对自我执行功能的逻辑感到困惑;所以,如果我想通过超时,请你确认我的逻辑是正确的:
n=1;
(function rec(n) {
rdb.setnx(lockkey, 'taken', function (err, lockvalue) {
if (err) {
console.error(err);
} else if (lockvalue == 1) {
// You have the lock; process it
//Release the key when you are done:
rdb.del(lockkey);
} else if (lockvalue == 0) {
// Key is taken by someone else; try again
setTimeout(function(){ rec(n++); }, 30<<n);
}
});
})();
答案 0 :(得分:1)
您可以使用递归函数,只需再次调用
(function rec() {
rdb.setnx(lockkey, 'taken', function (err, lockvalue) {
if (err) {
console.error(err);
} else if (lockvalue == 1) {
// You have the lock; process it
//Release the key when you are done:
rdb.del(lockkey);
} else if (lockvalue == 0) {
// Key is taken by someone else; try again
rec();
}
});
})();
如果需要,可以使用超时来延迟递归调用