Dart was built for constructing single-page applications. However, considering the prevalence of multicore processors in most computers, including mobile platforms, developers commonly utilize shared-memory threads that execute concurrently. Nonetheless, concurrency based on a shared state can lead to intricate and error-prone code. Hence, all code runs within isolates instead of threads in Dart.
Isolates function differently compared to threads. Each isolate has its memory heap, ensuring that the state of any isolate remains inaccessible from other isolates. They interconnect by passing messages through channels. Therefore, requiring a method to serialize messages. In Dart, isolates communicate through message passing as clients and servers.
We must add the following statement to our code to use isolates:
import 'dart:isolate';
We use Dart’s .spawn()
method to build an isolate. The syntax for the method is shown below:
Isolate <isolateName> = await Isolate.spawn( enter_parameter );
The <parameter>
represents the port receiving the message back.
We use the .kill()
method in Dart to kill an isolate. The syntax for the method is shown below:
isolateName.kill( <enter_parameter> );
spawn()
and kill()
methods together in a single programLet’s look at the code snippet below, where we create an isolate using the .spawn()
method, receive messages, and terminate the isolate using the .kill()
method.
// First we'll import the dart librariesimport 'dart:io';import 'dart:isolate';import 'dart:async';// Next, we create a new isolateIsolate isolate;void new_process() async{// We create a port for isolate to receive messages.ReceivePort portReceive= ReceivePort();// We start the isolateisolate = await Isolate.spawn(func, portReceive.sendPort);}void func(SendPort sendPort){int count = 0;// We print the output message every 1 sec.Timer.periodic(new Duration(seconds: 1), (Timer t) {// We increase the countercount++;//Next, we print the output messagestdout.writeln('Welcome to Educative $count');});}void end_process() {// We'll check the isolate with nullif (isolate != null) {stdout.writeln('Stop the Isolate');// Killing the isolateisolate.kill(priority: Isolate.immediate);// Setting the isolate to nullisolate = null;}}// Main Functionvoid main() async {stdout.writeln('Start the isolate');// We'll start the isolate with new_processawait new_process();// Assuming that the process takes 3 seconds to finishawait Future.delayed(const Duration(seconds: 3));// Here we call the end_processend_process();// Next we print the farewell messagestdout.writeln('Bye Bye!');// Finally, we exit the programexit(0);}
ReceivePort
for the isolate to receive messages..spawn()
method to instantiate the isolate with the receiving port created earlier.null
. We terminate the isolate using the .kill()
method.new_process()
print its messages to the console.Free Resources