gpt4 book ai didi

javascript - 锁的基本逻辑——互斥

转载 作者:IT王子 更新时间:2023-10-29 06:06:43 25 4
gpt4 key购买 nike

我正在为互斥锁的逻辑而苦苦挣扎;我在这里检查 key 是否被拿走,如果没有,我们拿走它,完成后释放它;但是你能帮我看看我怎样才能有一个循环来检查 key 直到它可用吗?

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();
}
});
})();

如果需要,可以使用超时来延迟递归调用

关于javascript - 锁的基本逻辑——互斥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28123381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com