锁的基本逻辑 – 互斥

我正在努力locking互斥的逻辑; 在这里我要检查钥匙是否被拿走,如果不是我们拿的话,什么时候放开钥匙; 但可以请你帮我怎样才能有一个循环来检查密钥,直到它变得可用?

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的回答。 我一直对自执行function的逻辑感到困惑, 所以如果我想通过暂停,请你确认我的逻辑是正确的:

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

你可以使用recursion函数,然后再调用它

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

如果需要,可以使用超时延迟recursion调用

    Interesting Posts