Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: could I use this library to implement a fixed number of shared locks #12

Closed
alastairtree opened this issue Dec 1, 2017 · 3 comments

Comments

@alastairtree
Copy link

I have a requirement to implement a distributed lock for a fixed number of clients, so the lock should allow for say 5 clients to acquire the lock, but the sixth client lock acquisition attempt should fail. Any suggestions for implementing this with this library? Thanks!

@madelson
Copy link
Owner

madelson commented Dec 1, 2017

Hi @alastairtree thanks for your interest in the library.

It sounds like what you are really looking for is a distributed semaphore. You may be interested in the discussion on this topic here: #7

In short, there is no automated way to do this with the current library although I am very interested in building one in if we can find a robust and performant implementation. Since you need only 5 concurrent clients, you could likely get away with simply looping over a set of 5 locks until one of them works:

class SqlDistributedSemaphore {
     private readonly IReadOnlyList<SqlDistributedLock> _locks;

     public SqlDistributedSemaphore(string lockName, int maxCount) 
     {
        this._locks = Enumerable.Range(0, maxCount).Select(i => new SqlDistributedLock(..., lockName: lockName + maxCount)).ToArray();
     }

     public IDisposable Acquire()
     {
            Random random = null;
            while (true)
            {
                for (var i = 0; i < this._locks.Count; ++i)
                {
                     var handle = this._locks[i].TryAcquire();
                     if (handle != null) { return handle; }
                }

                Thread.Sleep((random ?? random = new Random()).Next(50));
            }
     }
}

@madelson
Copy link
Owner

madelson commented Dec 1, 2017

Duplicate of #7

@madelson madelson marked this as a duplicate of #7 Dec 1, 2017
@madelson madelson closed this as completed Dec 1, 2017
@alastairtree
Copy link
Author

Super useful answer, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants