cppcoro icon indicating copy to clipboard operation
cppcoro copied to clipboard

Add async_shared_mutex synchronisation primitive

Open lewissbaker opened this issue 6 years ago • 0 comments

Cppcoro now has an async_mutex class which provides for exclusive locks in a critical section.

However, some data-structures could benefit from a reader/writer lock that allows multiple concurrent readers or a single exclusive writer.

Example usage:

template<typename T>
class concurrent_set
{
public:

  task<bool> try_add(T value)
  {
    // Mutating operations take out an exclusive lock
    auto lock = co_await m_mutex.lock_async();
    co_return m_set.insert(value).second
  }

  task<bool> try_remove(T value)
  {
    auto lock = co_await m_mutex.lock_async();
    co_return m_set.erase(value) > 0;
  }

  task<bool> contains(T value) const
  {
    // Allow concurrent readers by acquiring a shared lock.
    auto lock = co_await m_mutex.lock_shared_async();
    co_return m_set.find(value) != m_set.end();
  }

private:
  mutable async_shared_mutex m_mutex;
  std::unordered_set m_set;
};

It should be possible to allow a lock-free (but not wait-free) implementation of the async_shared_mutex class.

lewissbaker avatar Feb 21 '18 23:02 lewissbaker