lewissbaker / cppcoro

A library of C++ coroutine abstractions for the coroutines TS
MIT License
3.43k stars 472 forks source link

Add async_shared_mutex synchronisation primitive #66

Open lewissbaker opened 6 years ago

lewissbaker commented 6 years ago

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.