StackExchange / StackExchange.Redis

General purpose redis client
https://stackexchange.github.io/StackExchange.Redis/
Other
5.88k stars 1.51k forks source link

Counting Semaphore? #536

Open zlangner opened 7 years ago

zlangner commented 7 years ago

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?

NickCraver commented 6 years ago

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 commented 6 years ago

Tagging for #528

zlangner commented 5 years ago

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

illegalnumbers commented 3 years ago

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

DeepWorksStudios commented 11 months ago

Any updates?

kmcclellan commented 8 months ago

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...

zlangner commented 8 months ago

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.

mgravell commented 8 months ago

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)

kmcclellan commented 8 months ago

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 🙇‍♂️.