Nir
Nir

Reputation: 2629

redis distributed lock simple system

So I want to have a locking system where if the lock exists/acquired the other processes would wait (with timeout set up) until the lock is free and one of the waiting process would be able to acquire the lock.

Now in Redis this command pretty much gives what I want:

SET lock_key "locked" EX 10 NX

but if the key exists I get nil. How can I make it wait (using lua?) until the key does not exists anymore?

UPDATE:

Working on LUA solution (pseudo-code):

x=llen free 
y=llen lock 
if x+y =0 ; lpush free a
brpoplpush free lock 30
expire lock 600

I'm checking if the lists are empty, is so I add a value to free - this is sort of init to the locking. brpoplpush is the actual locking and wait if locked. the expire is for when the lock is not freed (for whatever reason) for 10 minutes.

Would love your thoughts

Upvotes: 0

Views: 600

Answers (1)

Nir
Nir

Reputation: 2629

echo -e "
eval \"if redis.call('llen', KEYS[1]) + redis.call('llen', ARGV[1]) == 0 then 
       redis.call('lpush', KEYS[1], 'a') end\" 1  free lock
brpoplpush free lock 30
expire lock 600" | redis-cli -h $REDIS

it is a mixture of pipeline and eval.

Upvotes: 1

Related Questions