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?
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.
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.
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.
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.
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++}');
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With