semaphore_plus 0.3.1 copy "semaphore_plus: ^0.3.1" to clipboard
semaphore_plus: ^0.3.1 copied to clipboard

Semaphore is a lightweight data type that is used for controlling the cooperative access to a common resource inside the isolate.

example/example.dart

import 'dart:async';

import 'package:semaphore_plus/semaphore_plus.dart';

Future<void> main(List<String> args) async {
  final maxCount = 3;
  final running = <int>[];
  var simultaneous = 0;
  final sm = LocalSemaphore(maxCount);
  final tasks = <Future>[];
  for (var i = 0; i < 9; i++) {
    tasks.add(Future(() async {
      try {
        await sm.acquire();
        running.add(i);
        if (simultaneous < running.length) {
          simultaneous = running.length;
        }

        print('Start $i, running $running');
        await _doWork(100);
        running.remove(i);
        print('End   $i, running $running');
      } finally {
        sm.release();
      }
    }));
  }

  await Future.wait(tasks);
  print('Max permits: $maxCount, max simultaneous runned: $simultaneous');
}

Future _doWork(int ms) {
  // Simulate work
  return Future.delayed(Duration(milliseconds: ms));
}
3
likes
150
points
7.11k
downloads

Publisher

verified publisheradrianjagielak.dev

Weekly Downloads

Semaphore is a lightweight data type that is used for controlling the cooperative access to a common resource inside the isolate.

Repository (GitHub)

Documentation

API reference

License

BSD-3-Clause (license)

More

Packages that depend on semaphore_plus