Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does creating a single ReceiverPort cause the Dart VM to hang?

e.g.:

import 'dart:isolate';

void main() { var p = new ReceivePort(); }

This will make the whole VM hang until I Ctrl-C it. Why is this?

like image 409
kirbyfan64sos Avatar asked Dec 04 '25 14:12

kirbyfan64sos


2 Answers

Dart's main function operates a bit differently than other platforms. It's more of an 'init' than anything else; it can exit and the application may continue running. A Dart VM application stays alive if it is listening for events. This generally means one or more open Streams. A ReceivePort is a Stream. Closing this stream would terminate the application.

You can verify this by running this script with dart --observe script.dart and viewing the application in Observatory. You'll notice that you have one isolate and it is 'idle' - this means there are ports open that are waiting for messages. You can click 'see ports' in the isolate panel and the ReceivePort will be the only item in the list. In general, if you are hanging and you can't figure out why, fire up Observatory and check which ports are open.

like image 177
Joe Conway Avatar answered Dec 06 '25 17:12

Joe Conway


A Dart isolate stays alive as long as it has something to do. If you start an asynchronous computation in main, then the isolate keeps running after main completes, waiting for the computation to complete. When there are no further computations running, the program ends.

A ReceivePort is a port that can receive data from somewhere else. As long as one of those are open, the isolate doesn't know that it's not done. A new event might arrive on the ReceivePort to trigger more computation. The isolate itself doesn't know whether anyone has a SendPort that can send it data, it just assumes that it's possible.

So, a ReceivePort keeps the isolate, and the program, alive because the program doesn't know for sure that it's not done computing yet. That's a good thing. You can create a new isolate and have it wait for commands on a ReceivePort without that isolate shutting down the first time it's idle.

It does mean that you need to close your ports when you are done.

like image 36
lrn Avatar answered Dec 06 '25 17:12

lrn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!