X-Git-Url: https://git.saurik.com/redis.git/blobdiff_plain/924aa408b99837036b679bd3895f836af6bc763f..49128f0b9da725de992e427fa341a837bcc2991b:/doc/SetnxCommand.html diff --git a/doc/SetnxCommand.html b/doc/SetnxCommand.html index 15a6c0e2..8c47e72d 100644 --- a/doc/SetnxCommand.html +++ b/doc/SetnxCommand.html @@ -16,7 +16,7 @@
SETNX works exactly like SET with the only difference thatif the key already exists no operation is performed.SETNX actually means "SET if Not eXists".
1 if the key was set 0 if the key was not set -
SETNX can also be seen as a locking primitive. For instance to acquirethe lock of the key foo, the client could try the following:+
+SETNX lock.foo <current UNIX time + lock timeout + 1> +
If SETNX returns 1 the client acquired the lock, setting the lock.fookey to the UNIX time at witch the lock should no longer be considered valid.The client will later use DEL lock.foo in order to release the lock.+
If SETNX returns 0 the key is already locked by some other client. We caneither return to the caller if it's a non blocking lock, or enter aloop retrying to hold the lock until we succeed or some kind of timeoutexpires.+
In the above locking algorithm there is a problem: what happens if a clientfails, crashes, or is otherwise not able to release the lock?It's possible to detect this condition because the lock key contains aUNIX timestamp. If such a timestamp is <= the current Unix time the lockis no longer valid.+
When this happens we can't just call DEL against the key to remove the lockand then try to issue a SETNX, as there is a race condition here, whenmultiple clients detected an expired lock and are trying to release it.+
Fortunately it's possible to avoid this issue using the following algorithm.Let's see how C4, our sane client, uses the good algorithm:+