Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Isolates As Workers

Edited to make the question more clear.

I am trying to work with Isolates (or Web Workers) in Dart. The only ways I can find to communicate between the main and isolate threads are send and call & then from the main thread. But that's a nice way for the main thread to pass some data to the isolate.

What's if I want the isolate to be the one who generates information? Like a game engine that does all the physics in a worker and then sends an updated world information to the main thread? In JavaScript you can send data at any time. Is there an efficient way in Dart? Or do I still have to wait for the main thread to call me and then pass it to it?

P.S. I wonder, does call & then block the thread until reply is done or not?

like image 578
Pijusn Avatar asked Apr 24 '12 16:04

Pijusn


People also ask

How does Dart isolate work?

Using isolates, your Dart code can perform multiple independent tasks at once, using additional processor cores if they're available. Isolates are like threads or processes, but each isolate has its own memory and a single thread running an event loop.

What is a Dart isolate?

An isolate is what all Dart code runs in. It's like a little space on the machine with its own, private chunk of memory and a single thread running an event loop. An isolate has its own memory and a single thread of execution that runs an event loop.

Does Dart support multithreading?

In a programming language like Java, developers can create multiple threads and share the same memory. Dart allows us to create multiple Isolates what is similar to multithreading, but it's not.

Is multithreading possible in flutter?

Since isolates are separate, we can have more than one isolate within our app, and that's how we can have multithreaded applications using dart. Most apps only need one event loop and one isolate running all of our code simultaneously.


1 Answers

As of Dart 1.0, you can use isolates like this:

import 'dart:isolate';
import 'dart:async';

void doStuff(SendPort sendPort) {
  print('hi from inside isolate');
  ReceivePort receivePort = new ReceivePort();
  sendPort.send(receivePort.sendPort);

  receivePort.listen((msg) {
    print('Received in isolate: [$msg]');
    sendPort.send('ECHO: $msg');
  });

}

void main() {
  SendPort sendPort;

  ReceivePort receive = new ReceivePort();
  receive.listen((msg) {
    if (sendPort == null) {
      sendPort = msg;
    } else {
      print('From isolate: $msg');
    }
  });

  int counter = 0;

  Isolate.spawn(doStuff, receive.sendPort).then((isolate) {
    new Timer.periodic(const Duration(seconds:1), (t) {
      sendPort.send('Count is ${counter++}');
    });
  });
}
like image 76
Seth Ladd Avatar answered Sep 28 '22 05:09

Seth Ladd