Skip to content

Instantly share code, notes, and snippets.

@xrad
Created September 14, 2023 17:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xrad/58e426b893f30484769d0c6593eeb7f8 to your computer and use it in GitHub Desktop.
Save xrad/58e426b893f30484769d0c6593eeb7f8 to your computer and use it in GitHub Desktop.
Simple Dart example to demonstrate shared memory for Isolates
import 'dart:ffi';
import 'dart:isolate';
import 'dart:io';
import 'package:ffi/ffi.dart';
void newIsolate(SendPort sendPort) {
final ptr = calloc.allocate<Int>(100);
ptr[0] = 42;
sendPort.send(ptr.address);
sleep(const Duration(seconds: 1));
ptr[0] = 43;
sleep(const Duration(seconds: 1));
print("Isolate terminating");
sendPort.send("end");
}
void mainIsolate() async {
ReceivePort recvPort = ReceivePort();
Isolate.spawn(newIsolate, recvPort.sendPort); // Starting myIsolate
recvPort.listen((message) {
if (message is int) {
// when message is an int, it must be the array address
final ptr = Pointer<Int>.fromAddress(message);
// we know have an array located at exactly the same address
// as in the isolate, poll [0] for a while
for (var i = 0; i < 15; i++) {
final val = ptr[0];
print("Value = $val");
sleep(const Duration(milliseconds: 100));
}
} else {
// when message is not int, it must be the "end" message
print("main terminating");
exit(0);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment