main function
Implementation
Future<void> main() async {
/// Example of protecting critical sections in different components
await databaseExample();
await fileSystemExample();
await concurrencyExample();
await hierarchicalLocking();
/// Print metrics to see what happened
log('Mutex metrics: ${MutexService().getMetrics()}');
final ReadWriteLock lock = ReadWriteLock('resource');
/// Reading operation
Future<void> performRead() async {
await lock.read(() async {
log('Reading data...');
await Future<dynamic>.delayed(const Duration(seconds: 1));
log('Read complete');
});
}
/// Writing operation
Future<void> performWrite() async {
await lock.write(() async {
log('Writing data...');
await Future<dynamic>.delayed(const Duration(seconds: 1));
log('Write complete');
});
}
/// Simulating concurrent reads and writes
await Future.wait(<Future<void>>[
performRead(),
performRead(),
performWrite(),
]);
/// Example resource pool with integers as resources
final ResourcePool<int> pool = ResourcePool<int>(<int>[1, 2, 3], 'int-pool');
Future<void> task(final String name) async {
await pool.use((final int resource) async {
log('$name acquired resource: $resource');
await Future<dynamic>.delayed(const Duration(seconds: 2)); // Simulating
log('$name released resource: $resource');
});
}
/// Simulate multiple concurrent tasks acquiring resources
await Future.wait(<Future<void>>[
task('Task A'),
task('Task B'),
task('Task C'),
task('Task D'),
]).then((final _) => log('All tasks completed'));
}