| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 import 'dart:async'; |
| 6 |
| 7 /// Mutual exclusion. |
| 8 /// |
| 9 /// Usage: |
| 10 /// |
| 11 /// var m = new Mutex(); |
| 12 /// |
| 13 /// await m.acquire(); |
| 14 /// try { |
| 15 /// // critical section |
| 16 /// } |
| 17 /// finally { |
| 18 /// m.release(); |
| 19 /// } |
| 20 class Mutex { |
| 21 Completer<Null> _lock; |
| 22 |
| 23 /// Acquire a lock. |
| 24 /// |
| 25 /// Returns a [Future] that will be completed when the lock has been acquired. |
| 26 Future<Null> acquire() async { |
| 27 while (_lock != null) { |
| 28 await _lock.future; |
| 29 } |
| 30 _lock = new Completer<Null>(); |
| 31 } |
| 32 |
| 33 /// Run the given [criticalSection] with acquired mutex. |
| 34 Future<T> guard<T>(Future<T> criticalSection()) async { |
| 35 await acquire(); |
| 36 try { |
| 37 return await criticalSection(); |
| 38 } finally { |
| 39 release(); |
| 40 } |
| 41 } |
| 42 |
| 43 /// Release a lock. |
| 44 /// |
| 45 /// Release a lock that has been acquired. |
| 46 void release() { |
| 47 if (_lock == null) { |
| 48 throw new StateError('No lock to release.'); |
| 49 } |
| 50 _lock.complete(); |
| 51 _lock = null; |
| 52 } |
| 53 } |
| OLD | NEW |