Concurrency in simple terms means the application is making progress in more than one task at a time. In a normal application or program, each line of code s executed sequentially, one after the other. But programs that use concurrency can run two functions simultaneously. If a time-consuming task is performed concurrently with other tasks, the throughput and the interactivity of the program can be improved.
Note: Concurrent programs may or may not be executed in parallel, depending on your machine (single-core / multi-core)
If you try concurrency in a single-core system, your CPU will just use a scheduling algorithm and switch between the tasks, so practically in single-core CPU tasks will make progress simultaneously but there will be no two tasks executing at the same time.
Concurrency in Dart:
In Dart, we can achieve concurrency by using the Isolates. As the name suggests isolates are isolated running blocks of codes. If you are familiar with threads you may think threads are similar to isolates. Although they provide the same functionality there is an internal difference between them. In a process, all threads share a common memory, on the other hand, isolates are independent workers that do not share memory but instead interconnect by passing a message over channels.
Dart provides the dart: isolate package to use the isolates in our program.
An isolate helps the program to take advantage of multicore microprocessors out of the box. There’s no way to share a variable between isolates—the only way to communicate between isolates is via message passing.
Normal Print 1 Normal Print 2 Normal Print 3 For!! From Isolate Geeks!! From Isolate Geeks!! From Isolate
Your output may differ.
Sometimes if you have a very complex function running on Isolate, then that function may not be executed completely.
Hello Main 1 Hello Main 2 Hello Main 3 Isolate Function 0 Isolate Function 1 Isolate Function 2 Isolate Function 3
Over here I have a for loop running on Isolate, but my for loop runs only for 4 iterations, that’s because when my for loop is iterating, the main function reaches its last line of execution. so the program kills the running isolate function.
Note: Your Output may differ.
If you want your isolate function to run completely then you can use- Asynchronous programming: futures, async, await
Hello Main 1 Hello Main 2 Hello Main 3 Isolate Function 0 Isolate Function 1 Isolate Function 2 Isolate Function 3 Isolate Function 4 Isolate Function 5 Isolate Function 6
If you want to learn more about Futures in Dart: Asynchronous programming in Dart