user385729
user385729

Reputation: 1984

basic logic of lock - mutual exclusion

I'm struggling with the logic of lock for mutual exclusion; Here Im checking if the key is taken or not, if not we take it and when done release it; but could you please help me how I can have a loop to check the key until it becomes available?

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

Your help is appreciated :-)

UPDATED:

Thanks so much Adeneco for the answer; I have always been confused with the logic of self executing function; so if I want to pass timeout could you please confirm my logic is right:

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

Upvotes: 2

Views: 137

Answers (1)

adeneo
adeneo

Reputation: 318182

You could use a recursive function, and just call it again

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

a timeout can be used to delay the recursive calls if neccessary

Upvotes: 1

Related Questions