锁的基本逻辑——互斥
basic logic of lock - mutual exclusion
我正在为互斥锁的逻辑而苦恼;我在这里检查密钥是否被拿走,如果没有,我们拿走它,完成后释放它;但是你能帮我看看我怎样才能有一个循环来检查密钥直到它可用吗?
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);
}
});
})();
你可以使用递归函数,然后再次调用它
(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();
}
});
})();
如果需要,可以使用超时来延迟递归调用
我正在为互斥锁的逻辑而苦恼;我在这里检查密钥是否被拿走,如果没有,我们拿走它,完成后释放它;但是你能帮我看看我怎样才能有一个循环来检查密钥直到它可用吗?
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);
}
});
})();
你可以使用递归函数,然后再次调用它
(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();
}
});
})();
如果需要,可以使用超时来延迟递归调用