Skip to content

Instantly share code, notes, and snippets.

@iota9star
Created October 7, 2022 13:26
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iota9star/e4c1821c75a35b5f024f84c4895a6eb1 to your computer and use it in GitHub Desktop.
Save iota9star/e4c1821c75a35b5f024f84c4895a6eb1 to your computer and use it in GitHub Desktop.
import 'dart:async';
class Mutex {
Completer<void>? _completer;
Future<void> lock() async {
while (_completer != null) {
await _completer!.future;
}
_completer = Completer<void>();
}
/// Notice: must be call [unlock] after [lock] method called to prevent the deadlock.
/// ```dart
/// final mutex = Mutex();
/// // ...
/// Future<void> doSth() async {
/// try {
/// await mutex.lock();
/// // do something...
/// } finally {
/// mutex.unlock();
/// }
/// }
/// ```
void unlock() {
final completer = _completer;
_completer = null;
completer?.complete();
}
Future<T> withLock<T>(FutureOr<T> Function() block) async {
try {
await lock();
return await block();
} finally {
unlock();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment