Chromium Code Reviews| 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 /// } | |
|
Brian Wilkerson
2017/08/25 16:56:44
You might consider adding a utility method similar
scheglov
2017/08/25 17:18:28
Done.
| |
| 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 /// Release a lock. | |
| 34 /// | |
| 35 /// Release a lock that has been acquired. | |
| 36 void release() { | |
| 37 if (_lock == null) { | |
| 38 throw new StateError('No lock to release.'); | |
| 39 } | |
| 40 _lock.complete(); | |
| 41 _lock = null; | |
| 42 } | |
| 43 } | |
| OLD | NEW |