Mutex class
Mutual Exclusion Lock Used to protect critical section of the code in order to avoid race conditions. It ensures FIFO lock accusation. Every acquirer gets the lock in order of when they asked for it, given it is released by the previous acquirer, if there is no previous acquirer then lock is acquired right away
Example:
class _Synchronized {
final _mutex = new Mutex();
final _values = new List<int>();
List<int> get values => this._values;
Future<void> execute(int milliseconds) async {
await this._mutex.lock();
try {
await Future.delayed(Duration(milliseconds: milliseconds));
this._values.add(milliseconds);
} finally {
this._mutex.release();
}
}
}
final synchronized = new _Synchronized();
final delays = List.generate(5, (index) => index * 1000).reversed;
final futures = delays.map((t) => synchronized.execute(t));
await Future.wait(futures);
print(synchronized.value)
The above code will print [4000, 3000, 2000, 1000, 0]
Constructors
- Mutex()
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
lock(
) → Future< void> -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
release(
) → void -
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited