3

I need a lock similar to the one from this answer from Stephen Cleary: https://stackoverflow.com/a/31194647/4381408

However, I also need to be able to lock on all keys at the same time. I'm using Stephen Cleary's AsyncEx library as well, so I thought of combining the AsyncDuplicateLock with an AsyncReaderWriterLock like this:

public sealed class AsyncDuplicateReaderWriterLock
{
    private AsyncReaderWriterLock _rwLock = new AsyncReaderWriterLock();
    private AsyncDuplicateLock _duplicateLock = new AsyncDuplicateLock();

    public IDisposable ReaderLock(object key)
    {
        return CollectionDisposable.Create(
                _rwLock.ReaderLock(),
                _duplicateLock.Lock(key)
            );
    }

    public async Task<IDisposable> ReaderLockAsync(object key)
    {
        return CollectionDisposable.Create(
            await _rwLock.ReaderLockAsync(),
            await _duplicateLock.LockAsync(key));
    }

    public IDisposable WriterLock()
    {
        return _rwLock.WriterLock();
    }

    public async Task<IDisposable> WriterLockAsync()
    {
        return await _rwLock.WriterLockAsync();
    }
}

This way, I can use ReaderLock to lock on a key, and WriterLock to lock on all keys. It's critical I get this right so I want to be sure that there's no way for this to deadlock or not lock properly. I don't feel confident enough about it.

So would this work, be somewhat efficient, and be threadsafe?

Thanks for the help!

1 Answer 1

3

I strongly, strongly advise you to take a step back, think about the actual problem you're trying to solve, explain it to someone else, and ask them how they would solve the concurrency issues.

That said, yes, you can (ab)use a reader/writer lock to do this. Personally, I would separate out the locking:

public IDisposable ReaderLock(object key)
{
  var rwKey = _rwLock.ReaderLock();
  var duplicateKey = _duplicateLock.Lock(key);
  return CollectionDisposable.Create(rwKey, duplicateKey);
}

// (and the same for async)

This makes it more obvious that the code is taking the RWL first (which it must do, in order to be correct).

1
  • Thanks for the answer as well as the advice. I'll rethink why this is even necessary and see if I need to make changes so that this locking mechanism isn't needed anymore. At the moment, some of the operations don't have a known key (yet) but do require locking for possible concurrency issues. Not sure if it's possible, but it's probably better to rewrite those operations so that locking is no longer necessary until I do have a key.
    – t.baart
    Mar 24, 2019 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.