StackExchange.Redis icon indicating copy to clipboard operation
StackExchange.Redis copied to clipboard

Counting Semaphore?

Open zlangner opened this issue 9 years ago • 9 comments

As described by RedisLabs one can implement a counting semaphore using Redis. Is there any plan to add a counting semaphore implementation to this package? I think it would be a good fit since it already support locking. What do you think?

zlangner avatar Dec 12 '16 15:12 zlangner

We'll visit this in the v2 pass. Not promises, but we're doing a full API evaluation and seeing what to add or change there.

NickCraver avatar May 28 '18 11:05 NickCraver

Tagging for #528

NickCraver avatar May 28 '18 11:05 NickCraver

Nick it looks like this didn't make it into the 2.0 milestone unless I'm missing it.

zlangner avatar Sep 16 '19 23:09 zlangner

Is this on a roadmap? Would be useful to have.

illegalnumbers avatar Dec 11 '20 19:12 illegalnumbers

Any updates?

s-beji avatar Oct 19 '23 03:10 s-beji

It appears that the "RedisLabs" link is broken. Can anyone point me in the right direction of how go about implementing a semaphore on top of SE.Redis?

My first idea was to use INCR and DECR, but this wouldn't support expiration/release very well in the event that a client disconnects unexpectedly. If latency wasn't an issue, I could designate n distinct keys and have clients cycle through them until an available one is found.

Perhaps something more efficient could be designed using a list or set to store the expirations? But I'm starting to feel like I am reinventing the wheel...

kmcclellan avatar Jan 11 '24 02:01 kmcclellan

I think you might be. FWIW Redis now has a page about the RedLock algorithm that includes numerous implementations of it.

I don't remember when exactly, but at some point over the 7 years since I started this thread I started to use one of the RedLock implementations and it's been working for my needs.

zlangner avatar Jan 11 '24 12:01 zlangner

A speculative unary lock: is pretty trivial to do these says - SET {key} {token} NX EX {timeout} - which is available via StringLock or LockTake; a speculative semaphore is usually implemented via Lua, so that you can check the current availability and optionally increment it (whether via a counter or a lpush/sadd) all in a single operation. However, both of these have the "speculative" problem, by which I mean it isn't a "and wait (with timeout) to be able to successfully take the lock/semaphore"; for that we need blocking operation support, and that is something we're currently talking to the redis folks about (blocking, multiplexing, protocol details, etc)

mgravell avatar Jan 11 '24 12:01 mgravell

Thanks, since posting I stumbled across @madelson's implementation in DistributedLock.Redis, which as you say leverages a lua script, and am quite happy with it. That library is a nice piece of work 🙇‍♂️.

kmcclellan avatar Jan 11 '24 20:01 kmcclellan