Compare-and-swap

370 views
Skip to first unread message

Garry Shutler

unread,
Oct 4, 2012, 11:21:26 AM10/4/12
to redi...@googlegroups.com
Hi,

I'm been looking at using redis to synchronize work between multiple processes and I was surprised to see there wasn't a compare-and-swap http://en.wikipedia.org/wiki/Compare-and-swap method available.

It's a well understood mechanism for synchronization and would make the locking process described in http://redis.io/commands/setnx a bit better as taking an expired lock would be done via CAS rather than GETSET which may replace a lock someone else has put in place (and avoid two people taking the same lock if they took it in the same millisecond). Also, it would make expiring a lock you hold safer as you wouldn't delete a newly created lock (had your lock expired), instead you could CAS the expiry date you set with one in the past.

Does that make sense? Is this a desirable feature? Is there something I'm overlooking?

I can look into creating a PR for this if needed but I don't know C so it might take me a while.

Cheers,

Josiah Carlson

unread,
Oct 4, 2012, 12:01:15 PM10/4/12
to redi...@googlegroups.com
This has been discussed before.

Prior answers:
1. Use a lock (written in the standard watch/multi/exec (this can be
tricky) or Lua)
2. Use Lua to write your compare-and-swap

Either of these lets you express *exactly* what you want without
having to guess.

If you have a limitation that you need to use a version of Redis
before scripting, or need it *now* and can't run one of the Redis
release candidates, then your option is basically to use a lock. Read
my article from January about building a correct lock:
http://dr-josiah.blogspot.com/2012/01/creating-lock-with-redis.html
... because incorrect locks can destroy data.

Regards,
- Josiah
> --
> You received this message because you are subscribed to the Google Groups
> "Redis DB" group.
> To post to this group, send email to redi...@googlegroups.com.
> To unsubscribe from this group, send email to
> redis-db+u...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/redis-db?hl=en.

Garry Shutler

unread,
Oct 4, 2012, 12:34:36 PM10/4/12
to redi...@googlegroups.com
Ok, thanks Josiah. Not sure how I hadn't put two and two together on that, the transactions page http://redis.io/topics/transactions even mentions check-and-set (CAS).

Garry Shutler

www.robustsoftware.co.uk | @gshutler
Reply all
Reply to author
Forward
0 new messages