Open bsutton opened 8 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');
}
I think the issue is not really how mailbox works, but no way to synchronously spawn isolates.
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.