dart-lang / labs

This repository is home to Dart 'labs' packages.
BSD 3-Clause "New" or "Revised" License
21 stars 2 forks source link

timing issue establishing a mailbox #11

Open bsutton opened 8 months ago

bsutton commented 8 months ago

DCli is attempting to use a mailbox to spawn process synchronously.

My primary isolate spawns a secondary isolate which runs a process.

The primary isolate needs to call take() to receive the secondary isolate's send port.

The issue is that we have a timing problem.

If I call take() in the primary isolate before the secondary isolate has a chance to spawn then take() essentially blocks the secondary isolate from spawning.

I can't use an await when spawning the secondary isolate as the core reason for using a mailbox is to spawn the process synchronously.

bsutton commented 7 months ago

This code demonstrates the problem. As you can see it requires main to be async, which means we don't have a sync solution dispite the use of mailbox.


void main() async {
  final mailbox = Mailbox();

  void request(String msg) {
    print('sending $msg');
    final response = ascii.decode(mailbox.sendRequest(ascii.encode(msg)));
    print('got back: $response');
  }

  final worker = await Isolate.spawn((mailboxAddr) {
    print('Isolate is running');
    Mailbox.fromAddress(mailboxAddr).messageLoop((mailbox, msg) {
      final str = ascii.decode(msg);
      if (str == 'exit') {
        mailbox.isRunning = false;
      }
      print('got $str from mailbox, responding');
      return ascii.encode('response($str)');
    });
    print('Isolate is done');
  }, mailbox._mailbox.address);

  for (var i = 0; i < 5; i++) {
    request('request #$i');
  }
  request('exit');
}
ntkme commented 3 months ago

I think the issue is not really how mailbox works, but no way to synchronously spawn isolates.