Introduction
In this article, we will be learning about the concurrency in dart. Concurrency is a mechanism that allows us to run multiple tasks simultaneously. In programming languages, we use this concept to run multiple code blocks concurrently. In this mechanism, we use the idea of multi-core processors to divide the work for different processors, and these processors execute the code concurrently. Generally, we execute multiple functions at the same time e.g. along with the main function, other functions are also executing and producing results.
If your CPU is a uniprocessor, then concurrency will not support because, in that case, when the CPU gets the new process, a simple scheduling algorithm will run, and the old process will get preempted.
How Dart Supports Concurrency
In dart, we can use the concurrency mechanism with the help of isolates. Isolates are the block of code running isolated on the processor. You may find isolates relatable to java's thread. If you don't know about the thread, read this article on the java thread. The main difference between thread and isolates is thread runs on the same shared memory while the isolates have their own individual memory, they do not have shared variables. The only way they can communicate is through messages which are sent at the time of creating the isolates.
To use the isolate in your code, you need to import its library first.
import 'dart:isolate';
Syntax:
Isolate.spawn(New_Function, 'Message to be passed');
Isolate class in dart provides us with a static method called spawn. When we call the spawn method with the new function as the argument, the new function is invoked as a new isolate with only the message as a parameter.
The output of the code in a concurrent manner may differ from system to system we cannot simply decide the execution serial of the different functions in the concurrent background.
Example: In the example given below, we have two types of outputs for the same code executed two different times.
Code:
import 'dart:isolate';
void newFunction(var message) {
// This is our isolate function.
print('${message} inside Isolate');
}
void main() {
// Calling the isolate function with new function and message.
Isolate.spawn(newFunction, 'Hello fellas!');
Isolate.spawn(newFunction, 'Coding');
Isolate.spawn(newFunction, 'Ninjas');
// Printing the message from the function.
print('First message from main function');
print('Second message from main function');
}
Output 1:
Hello fellas! inside Isolate
First message from main function
Second message from main function
Coding inside Isolate
Ninjas inside Isolate
Output 2:
First message from main function
Second message from main function
Hello fellas! inside Isolate
Ninjas inside Isolate
Coding inside Isolate





