• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import 'dart:async';
2import 'dart:isolate';
3
4import 'package:ejdb2_dart/ejdb2_dart.dart';
5
6/// Database access from multiple isolates.
7/// Based on isolate example from https://github.com/adamlofts/leveldb_dart
8
9void main() async {
10  final runners = Iterable<int>.generate(5).map((int index) {
11    return Runner.spawn(index);
12  }).toList();
13  await Future.wait(runners.map((Runner r) => r.finish));
14}
15
16Future<void> run(int index) async {
17  print('Thread ${index} write');
18  final db = await EJDB2.open('isolate.db', truncate: true);
19  await db.put('c1', {'index': index});
20  // Sleep 1 second
21  await Future<void>.delayed(const Duration(seconds: 1));
22  final nextKey = (index + 1) % 5;
23  final doc = await db.createQuery('/[index=:?]', 'c1').setInt(0, nextKey).execute().first;
24  print('Thread ${index} read: ${doc}');
25}
26
27class Runner {
28  final Completer<void> _finish = Completer<void>();
29  final RawReceivePort _finishPort = RawReceivePort();
30  Runner.spawn(int index) {
31    _finishPort.handler = (dynamic _) {
32      _finish.complete();
33      _finishPort.close();
34    };
35    Isolate.spawn(run, index, onExit: _finishPort.sendPort);
36  }
37  Future<void> get finish => _finish.future;
38}
39