0

I wish a task not to be ran at same time by many users. So I used this code:

REDIS_CLIENT = redis.Redis()
lock = REDIS_CLIENT.lock("task_key", timeout=60)
have_lock = lock.acquire(blocking=True, blocking_timeout=60)

With 2 users, it works well. But with more than 2 users :

  1. User 1 acquires lock for the task
  2. User 1 runs task
  3. User 2 tries acquiring lock for the task but it is already acquired so he waits
  4. User 3 tries acquiring lock for the task but it is already acquired so he waits
  5. User 1 task ends
  6. User 3 acquires lock for the task
  7. User 3 runs task
  8. User 2 get angry because User 3 stole his place

At step 6, User 2 or User 3 can acquire lock randomly. But I would like to be sure User 2 acquires it first.

How to set a priority ?

PS : I use Redis to run "unique" tasks with celery : https://stackoverflow.com/a/19499540/5077962

Rom1
  • 346
  • 4
  • 17

1 Answers1

0

How to set a priority ?

That's not a thing.

The issue is known as "lock fairness". If your redis client doesn't implement fair locks then your only option is to handroll it e.g. based on the fair semaphore recipe.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • On the link you gave me, it says we want "to prevent clients on systems with slower system clocks [to steal] the semaphore from clients on systems with faster clocks". I think that's not my point because all my requests are done on the same machine. Then, clock should be the same. – Rom1 Oct 11 '21 at 12:27
  • Anyway, if it does solve my problem, would you advice a python redis client which implements lock fairnesss please ? – Rom1 Oct 11 '21 at 13:40