Reputation: 727
I am studying the locking method on Redis, and found this official documents https://redis.io/commands/setnx#handling-deadlocks
My understanding is that SETNX
is an atomic operation and ONLY ONE client can do it successful (get 1
) and the others failed (get 0
)
However in the section Handling deadlocks
on this document, it said:
1) C1 and C2 read lock.foo to check the timestamp, because they both received 0 after executing SETNX, as the lock is still held by C3 that crashed after holding the lock.
2) C1 sends DEL lock.foo
3) C1 sends SETNX lock.foo and it succeeds
4) C2 sends DEL lock.foo
5) C2 sends SETNX lock.foo and it succeeds
ERROR: both C1 and C2 acquired the lock because of the race condition.
My question is that why 3) and 5) can be succeed? I think only C1 or C2 can be succeed but not both.
Please correct my understanding, thank you,.
Upvotes: 1
Views: 2678
Reputation: 48952
SETNX
only sets the key if it doesn't already exist. So, indeed, if multiple clients try to SETNX
at the same time, only one will succeed.
But in this case (see steps 2 and 4), the clients are deleting the key before calling SETNX
. Since the key no longer exists, there is nothing to prevent SETNX
from succeeding.
Upvotes: 4