Skip to content

Move semantics for SendPort #49587

Open
Open
@gaaclarke

Description

@gaaclarke

This tracker is for issues related to:

  • Dart VM

Description

We should be able to transfer any object over SendPort in constant time if we know:

  1. Isolates share a heap
  2. There is one reference to an object
  3. The object is never used again after it is sent to a SendPort

To make this possible I propose we add a new class called Unique that when constructed sent over a SendPort asserts that there is one reference to each object in the object graph and nulls out its reference. That way we can have constant-time communication of any object over SendPorts. It isn't asserted at compile time, but this might be the best we can do with Dart.

The printed timestamps should almost be the same, today the difference is 12s locally:

// @dart=2.12
import 'dart:isolate';

class Unique<T> {
  T? get value => _value;
  T? _value;
  Unique(this._value) {
    // Crawl through the object tree and ensure there is only one reference to
    // each object, otherwise throw exception.
    // assert(isUnique(_value));
  }
}

Map<String, Object> makeLargeMap(int n) {
  Map<String, Object> result = {};
  for (int i = 0; i < n; ++i) {
    result[i.toString()] = i;
  }
  return result;
}

void isolateMain(SendPort sendPort) {
  ReceivePort receivePort = ReceivePort();
  sendPort.send(receivePort.sendPort);
  receivePort.listen((message) {
    var foo = Unique<Map<String, Object>>(makeLargeMap(message));
    print(DateTime.now().millisecondsSinceEpoch);
    sendPort.send(foo);
    // assert(foo.value == null);
  });  
}

void main() async {
  ReceivePort receivePort = ReceivePort();
  Isolate.spawn(isolateMain, receivePort.sendPort);
  SendPort sendPort = await receivePort.first;
  sendPort.send(10000000);
  print(await receivePort.first);
  print(DateTime.now().millisecondsSinceEpoch);
}

Related language request for move semantics: dart-lang/language#2355 (this has compile time checks for uniqueness)
cc @mkustermann

Alternatives considered

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-vmUse area-vm for VM related issues, including code coverage, and the AOT and JIT backends.type-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions