Dart Isolates' pause function not working as expected
Asked Answered
L

1

6

I've been playing around with Dart Isolates and have run into a problem using the isolate.pause(); function.

import 'dart:io';
import 'dart:isolate';

main(){
  ReceivePort receivePort = new ReceivePort();
  Isolate.spawn(isolateEntryPoint, receivePort.sendPort).then((isolate){
    isolate.pause(isolate.pauseCapability);
  });
}

void isolateEntryPoint(SendPort sendPort){
  while(true){
    print("isolate is running");
    sleep(new Duration(seconds: 2));
  }
}

In my example the isolate basically just prints something out every 2 seconds.

From what I read on the docs, my understanding is that the above code should:

  1. Spawn an isolate
  2. Promptly pause that isolate

But it's not working, the isolate is still running and printing "isolate is running" every 2 seconds even after I tell it to pause.

I'm aware that you can start an isolate in a paused state by passing in the paused: true optional parameter: Isolate.spawn(isolateEntryPoint, receivePort, paused: true).... Ultimately however I would like to be able to pause the isolate at any point, not just right off the bat.

The only documentation I could find about using this was on the official dart docs, so it's possible I'm using the isolate.pause() function incorrectly. But either way a code example demonstrating the correct usage of this function would be greatly appreciated.

Lakitalaks answered 6/1, 2018 at 18:5 Comment(0)
N
9

You are correct that this is not working as you expected.

The isolate pause functionality works by pausing the event queue. The currently executing event will complete, and then no further events are processed until you resume the isolate. The pause does not affect running code.

In this code, the isolate entry point is running an infinite loop with a built-in delay. It never returns to the event queue. If you scheduled any asynchronous operations in the loop, they would never execute. The sleep primitive sleeps the entire isolate, but it's no different from doing nothing at all (it just takes longer).

You try to "promptly pause" the new isolate, but isolates run concurrently, and the new isolate has already started executing its entry point function when the Isolate object is returned.

It might be possible to change the isolate functionality in the future, to be more eager in handling control messages, if we don't have to support isolates compiled to JavaScript any more, but currently isolates control messages are effectively asynchronous, they only take effect between the events of the Dart event queue.

Neela answered 8/1, 2018 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.