lockShared method

Future<void> lockShared({
  1. Duration? timeLimit,
})

Aquires a shared lock.

This is mutually exclusive with other users aquiring the exclusive lock.

But, this can be shared with all the other users aquiring shared locks.

This is useful for read-only users of resources running asynchronously at the same time.

If timeLimit is not null, this might throw TimeoutException after timeLimit.

Implementation

Future<void> lockShared({Duration? timeLimit}) async {
  if (_isLocked || _waitingQueue.isNotEmpty) {
    var myCompleter = Completer<void>.sync();
    _waitingQueue.add(myCompleter);
    if (timeLimit == null) {
      await myCompleter.future;
    } else {
      await myCompleter.future.timeout(timeLimit, onTimeout: () {
        _waitingQueue.remove(myCompleter);
        return Future.error(TimeoutException(
            'lockShared: Timed out during awating the exclusive lock released'));
      });
    }
    _waitingQueue.removeAt(0);
  }
  if (_sharedCount == 0) {
    _shared = Completer<void>();
  }
  _sharedCount++;
  if (_waitingQueue.isNotEmpty) {
    _waitingQueue[0].complete();
  }
}