lock method
Aquires the exclusive lock.
This is literally mutually exclusive with other users aqurering exclusive/ shared locks.
- waits for the other existing users having requested for aquiring the exclusive lock at the call time to release it.
- makes the other users wait for newly aquiring exclusive/ shared locks.
- waits for all the existing users having aquired shared locks to release them.
This is useful for a read/ write user of resouces which should not run with other users at the same time.
If timeLimit
is not null
, this might throw TimeoutException
after timeLimit
* 2, at max.
1 timeLimit
for awaiting the exclusive lock released,
and 1 timeLimit
for awaiting shared locks released.
Implementation
Future<void> lock({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(
'lock: Timed out during awating the exclusive lock released'));
});
}
_waitingQueue.removeAt(0);
}
_isLocked = true;
if (_sharedCount > 0) {
if (timeLimit == null) {
await _shared.future;
return;
}
await _shared.future.timeout(timeLimit, onTimeout: () {
_isLocked = false;
return Future.error(TimeoutException(
'lock: Timed out during awating shared locks released'));
});
}
}