Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(14)

Unified Diff: pkg/analyzer/lib/src/dart/analysis/mutex.dart

Issue 3006563003: Implement Mutex for Dart. (Closed)
Patch Set: Add Mutex.guard(). Created 3 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | pkg/analyzer/test/src/dart/analysis/mutex_test.dart » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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..562d56f5d7bc87b9c59ccc027e13a01d26600d44
--- /dev/null
+++ b/pkg/analyzer/lib/src/dart/analysis/mutex.dart
@@ -0,0 +1,53 @@
+// 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();
+/// }
+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>();
+ }
+
+ /// Run the given [criticalSection] with acquired mutex.
+ Future<T> guard<T>(Future<T> criticalSection()) async {
+ await acquire();
+ try {
+ return await criticalSection();
+ } finally {
+ release();
+ }
+ }
+
+ /// 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;
+ }
+}
« no previous file with comments | « no previous file | pkg/analyzer/test/src/dart/analysis/mutex_test.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698