Created
October 7, 2022 13:26
-
-
Save iota9star/e4c1821c75a35b5f024f84c4895a6eb1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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