Chromium Code Reviews| Index: pkg/analyzer/lib/src/dart/analysis/mutex.dart |
| diff --git a/pkg/analyzer/lib/src/dart/analysis/mutex.dart b/pkg/analyzer/lib/src/dart/analysis/mutex.dart |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..ceaac21f17d665438fd50d019ded3074839151e5 |
| --- /dev/null |
| +++ b/pkg/analyzer/lib/src/dart/analysis/mutex.dart |
| @@ -0,0 +1,43 @@ |
| +// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file |
| +// for details. All rights reserved. Use of this source code is governed by a |
| +// BSD-style license that can be found in the LICENSE file. |
| + |
| +import 'dart:async'; |
| + |
| +/// Mutual exclusion. |
| +/// |
| +/// Usage: |
| +/// |
| +/// var m = new Mutex(); |
| +/// |
| +/// await m.acquire(); |
| +/// try { |
| +/// // critical section |
| +/// } |
| +/// finally { |
| +/// m.release(); |
| +/// } |
|
Brian Wilkerson
2017/08/25 16:56:44
You might consider adding a utility method similar
scheglov
2017/08/25 17:18:28
Done.
|
| +class Mutex { |
| + Completer<Null> _lock; |
| + |
| + /// Acquire a lock. |
| + /// |
| + /// Returns a [Future] that will be completed when the lock has been acquired. |
| + Future<Null> acquire() async { |
| + while (_lock != null) { |
| + await _lock.future; |
| + } |
| + _lock = new Completer<Null>(); |
| + } |
| + |
| + /// Release a lock. |
| + /// |
| + /// Release a lock that has been acquired. |
| + void release() { |
| + if (_lock == null) { |
| + throw new StateError('No lock to release.'); |
| + } |
| + _lock.complete(); |
| + _lock = null; |
| + } |
| +} |