Created
October 7, 2022 13:26
-
-
Save iota9star/e4c1821c75a35b5f024f84c4895a6eb1 to your computer and use it in GitHub Desktop.
Revisions
-
iota9star created this gist
Oct 7, 2022 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,40 @@ 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(); } } }