Concurrent Programming with Isolates

  • Concurrent Programming with Isolates

Concurrency in Dart

Concurrency is the execution of several instruction sequences at the same time. It ivolves performing more than one task simultaneoulsy. Concurrent Programming in Dart is handled with Isolates. Isolates are independent workers that run in separate memory spaces, allowing for true parallel/simultaneous execution.

Concurrency with Isolates

Isolates are isolated units of running code.They communicate by passing messages, which makes them a poweful tool for handling concurrent tasks in Dart. The dart:isolate package is used for concurrency that make use of hardware available. They do not share variable directly instead, they communicate via message passing.

Creating and Communicating with an Isolate

  • Import the ‘dart:isolate’ library.
  • pawn an isolate using the ‘Isolate.spawn’ method.
  • SetUp communication between tha main isolate and the spawned isolate using ‘ReceivePort’ and ‘SendPort’.

Example

import 'dart:isolate';  
void fo(var message){ 
   print('execution from fo ... the message is :${message}'); 
}  
void main(){ 
   Isolate.spawn(fo,'Hello!!'); 
   Isolate.spawn(fo,'Greetings!!'); 
   Isolate.spawn(fo,'Welcome!!'); 
   
   print('execution from main1'); 
   print('execution from main2'); 

}

Output1

execution from main1 
execution from main2 
execution from main3 
execution from fo ... the message is :Hello!! 

Output2

execution from main1 
execution from main2 
execution from main3 
execution from fo ... the message is :Welcome!! 
execution from fo ... the message is :Hello!!
execution from fo ... the message is :Greetings!!

The above output will be different for different hardware and operating system configurations.