Dart Concurrency

In this tutorial you will learn about the Dart Concurrency and its application with practical example.

What Is Concurrency?

Concurrency is the ability to run multiple programs or multiple parts of a program in parallel. If a time consuming task can be performed asynchronously or in parallel, this improve the throughput and the interactivity of the program. Concurrency enable a program to achieve high performance and throughput by utilizing the untapped capabilities of underlying operating system and machine hardware.

Dart Concurrency

Dart uses isolates in order to achieve concurrency. Isolates are independent workers that do not share memory, but instead communicate by passing messages over channels, isolates are similar to actors in Erlang or web workers in JavaScript. Since isolates are communicating via passing messages thus it needs a way to serialize a message. This is done using a snapshot, which is generated from a given object, and then this is transferred to another isolate for deserializing. Dart uses Isolates for Concurrent programming. It is as a tool for doing works in parallel. The dart:isolate package is a set of classes required achieve concurrency using Isolates.

Example:-

Here, the spawn method of the Isolate class facilitates running a function sayHello in parallel with the rest of our code. The spawn function takes following two parameters –

1.) The function to be spawned.
2.) An object that will be passed to the spawned function.

If no object is pass to the spawned function, it will be provided with a NULL value.

The two functions (sayHello and main) not necessarily run in the same order each time program executed. There is no guarantee when sayHello will be executing and when main() will be executing. The output will be different each time you run program.

Output:-

dart_concurrency_example

Note:- The output of the above program will be different for different hardware and operating system configurations.

In this tutorial we have learn about the Dart Concurrency and its application with practical example. I hope you will like this tutorial.