DEV Community

kyorohiro (kiyohiro kawamura)
kyorohiro (kiyohiro kawamura)

Posted on

About Dart's Isolate (1)

I want to explain about How to distribute the load with Isolate.
And In this Document, I'll confirm about isolate basic usage before explain it.

Hello Isolate

We can write multi-threads like programming code to use Isolate.

import 'dart:isolate' as iso; onMain(message) async { // print("child:arg:${message}"); for (var i = 0; i < 5; i++) { await Future.delayed(Duration(milliseconds: 100)); print("child:print:${i}"); } } main() async { iso.Isolate.spawn(onMain, "Hi"); for (var i = 0; i < 5; i++) { await Future.delayed(Duration(milliseconds: 100)); print("parent:print:${i}"); } } 
Enter fullscreen mode Exit fullscreen mode
$ dart bin/main_example_isolate_01.dart child:arg:Hi parent:print:0 child:print:0 parent:print:1 child:print:1 parent:print:2 child:print:2 parent:print:3 child:print:3 parent:print:4 
Enter fullscreen mode Exit fullscreen mode

Communication For Each Isolate

Parent Isolate and Child Isolate can not share memory.
if you want to share data both isolate, you must to use SendPort and ReceivePort.

import 'dart:isolate' as iso; onMain(message) async { // print("child:arg:${message}"); iso.SendPort sendPort = message['p']; for (var i = 0; i < 5; i++) { await Future.delayed(Duration(milliseconds: 100)); print("child:print:${i}"); sendPort.send("hi${i}"); } } main() async { iso.ReceivePort receivePort = iso.ReceivePort(); receivePort.listen((message) { print("parent:onMessage: ${message}"); }); iso.Isolate.spawn(onMain, {"v": "Hi", "p": receivePort.sendPort}); for (var i = 0; i < 5; i++) { await Future.delayed(Duration(milliseconds: 100)); print("parent:print:${i}"); } receivePort.close(); } 
Enter fullscreen mode Exit fullscreen mode
$ dart bin/main_example_isolate_02.dart child:arg:{v: Hi, p: SendPort} parent:print:0 child:print:0 parent:onMessage: hi0 parent:print:1 child:print:1 parent:onMessage: hi1 parent:print:2 child:print:2 parent:onMessage: hi2 parent:print:3 child:print:3 parent:onMessage: hi3 parent:print:4 child:print:4 parent:onMessage: hi4 
Enter fullscreen mode Exit fullscreen mode

Next

More Isolate
https://github.com/kyorohiro/hao_dart_server_and_systemd/blob/master/bin/main_example_isolate.dart

Top comments (1)

Collapse
 
kyorohiro profile image
kyorohiro (kiyohiro kawamura)

Isoalte for Web is here

dev.to/kyorohiro/isolate-at-flutte...