• Lewis Baker's avatar
    Add folly::coro::Mutex · 48a1dd79
    Lewis Baker authored
    Summary:
    Adds an async Mutex that allows a coroutine to `co_await` acquiring the lock on a mutex.
    
    This mutex is not cancellable and does not support timeouts, but is very efficient
    and does not require any per-operation memory allocations (memory for tracking the list of waiting coroutines is borrowed from the awaiting coroutine frame).
    
    The Mutex class provides fair locking by implementing a FIFO queue of waiting coroutines.
    ie. coroutines will acquire the lock in the order that they await the lock operation.
    This could be relaxed in the future if needed to provide bounded wait-times but not necessarily FIFO order.
    
    Example usage:
    ```c++
    template<typename T>
    class ConcurrentStack
    {
      folly::coro::Mutex mutex_;
      std::vector<T> values_;
    public:
      coro::Task<void> pushAsync(T value)
      {
        auto lock = co_await mutex_.scopedLockAsync();
        values_.push_back(value);
      }
    
      coro::Task<Optional<T>> tryPopAsync()
      {
        auto lock = co_await mutex_.scopedLockAsync();
        if (values_.empty()) co_return Optional<T>{};
        T result = values_.back();
        values_.pop_back();
        co_return result;
      }
    };
    ```
    
    Reviewed By: andriigrynenko
    
    Differential Revision: D9209637
    
    fbshipit-source-id: 4b81c8f33b9fc39781f4237d1821b0e0b2e4f3c5
    48a1dd79
MutexTest.cpp 3.66 KB