Skip to content

Instantly share code, notes, and snippets.

@iota9star
Created October 7, 2022 13:26
Show Gist options
  • Save iota9star/e4c1821c75a35b5f024f84c4895a6eb1 to your computer and use it in GitHub Desktop.
Save iota9star/e4c1821c75a35b5f024f84c4895a6eb1 to your computer and use it in GitHub Desktop.

Revisions

  1. iota9star created this gist Oct 7, 2022.
    40 changes: 40 additions & 0 deletions mutex.dart
    Original 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();
    }
    }
    }