async_locks 4.0.2 copy "async_locks: ^4.0.2" to clipboard
async_locks: ^4.0.2 copied to clipboard

Synchronization primitives for asynchronous Dart code: Event, Lock and Semaphore

example/example.dart

/// Synchronization to avoid concurrent write to a file
import "dart:io";

import "package:async_locks/async_locks.dart";

class Program {
  final lock = Lock();
  final file = File("example.test");

  Future<void> runFuture(int n) async {
    // Concurrent write (in append mode) to the example file.
    // Race conditions can occur without synchronization. Try removing the lock and see what happens.
    await lock.run(() async => await file.writeAsString("Writing from Future-$n\n", mode: FileMode.append, flush: true));
  }

  Future<void> run() async {
    // Wait for 4 futures
    await Future.wait([runFuture(1), runFuture(2), runFuture(3), runFuture(4)]);

    // Read and print file content to stdout
    final content = await file.readAsString();
    print(content);
  }
}

void main() async {
  final program = Program();

  // Write header to example file
  await program.file.writeAsString("EXAMPLE FILE\n");

  // Run futures with potential race conditions
  await program.run();
}
copied to clipboard
7
likes
160
points
2.23k
downloads

Publisher

verified publisherharuka39.me

Weekly Downloads

2024.07.06 - 2025.01.18

Synchronization primitives for asynchronous Dart code: Event, Lock and Semaphore

Repository (GitHub)
View/report issues

Topics

#async #concurrency #lock #mutex

Documentation

API reference

License

GPL-3.0 (license)

More

Packages that depend on async_locks