ossa 1.0.4 ossa: ^1.0.4 copied to clipboard
A simple package for working with multithreading, using an interface similar to tasks in C#.
Hello World #
void main() async {
// Create and run Task using run method
var task = await Task.run((context) {
print('Hello, from task!');
});
// Wait when task is completed
await task.result();
}
Get result from task #
void main() async {
// Create and run Task with double return type using run method
var task = await Task.run<double>((context) => 3 * 7);
// Wait result from Task
var result = await task.result();
print(result);
}
Parallel algorithm #
void main() async {
// We have some initial data
var data = List<double>.generate(5, (index) => index.toDouble());
var tasks = <Task<double>>[];
for (var i = 0; i < data.length; i++) {
// Create and run task with run method, passing data to task
tasks.add(await Task.run<double>((context) {
var number = context.get<double>('number');
return number * number;
}, data: {'number': data[i]}));
}
// Wait when all task is completed
var results = await Future.wait<double>(List<Future<double>>.generate(
tasks.length, (index) => tasks[index].result()));
for (var result in results) {
print(result);
}
}