worker_pool 0.0.5
worker_pool: ^0.0.5 copied to clipboard
A Dart/Flutter package for managing a pool of isolates to execute tasks concurrently, with support for resource management, constant sharing, and proper cleanup.
example/worker_pool_example.dart
import 'package:worker_pool/worker_pool.dart';
// 1. Define a function to be executed in an isolate.
// This function can be a top-level function or a static method.
Future<int> fibonacci(int n) async {
if (n <= 1) return n;
// This is not an efficient implementation of fibonacci, but it is a good example of a CPU-bound task.
return await fibonacci(n - 1) + await fibonacci(n - 2);
}
void main() async {
// 2. Create a configuration for the worker pool.
// Register the function you want to run in the isolates.
final config = WorkerPoolConfig(predefinedFunctions: {'fib': fibonacci});
// 3. Initialize the worker pool.
final pool = await WorkerPool.initialize(config);
print(
'Worker pool initialized with ${pool.getStatistics()['totalWorkers']} workers.',
);
// 4. Submit a task to be executed.
// Use the registered function name.
final argument = 40;
print('Submitting task: fib($argument)');
try {
final result = await pool.submit<int, int>('fib', argument);
print('Result of fib($argument) is $result');
} catch (e) {
print('An error occurred: $e');
}
// 5. Dispose the pool when you're done.
await pool.dispose();
print('Worker pool disposed.');
}