Wednesday, November 24, 2021

Dart: Isolate

Lately, I have been working on a janky-improvement issue in a Flutter application, so I have a chance to understand a little bit how Dart supports the asynchronous programming - despite of being a Single Thread Language.
Here is the key you will need to remember is: Dart does one task a time. Once a task is running, everything is blocked waiting for its finish.
When a Dart app is started, an instance of the isolate is created by DartVM automatically and you can run your "main" code on it - we can call it Main Isolate (Isolate is not a thread, though they share some similar context). The process is:
  1. Make 2 FIFO queues named "MicroTask Queue" and "Event Queue"
  2. Run main() function until it's complete
  3. Run Event Loop

Event loop

  • Event loop is an infinite loop. It is there to check if no task remains on Micro Task Queue, then it will push the tasks from Event Queue to main Isolate and working on it.
  • MicroTask Queue: short time tasks for internal event that need to be done before return back to Event Queue
  • Event Queue: all tasks from external events like I/O, gesture, drawing, timers, streams, future, async, await... So, onPressed is waiting for a tap, and the future is waiting for network data, but from Dart’s perspective, those are both just events in the Event Queue - these APIs are all just ways for you to tell Dart’s event loop, "Here’s some code, please run it later."

Isolate

You can think about Isolate as a simple computer, with some `Memory`, a Single Thread, and an Event Loop. The idea is to move the heavy task to another computer that you don't interact to so you don't feed it janky (:D)

What is differences between Isolate and Thread

  • AFAIK the isolate is like its name, quite isolation, have own resources, zone, limitation.
  • Does not share heap memory between each other
  • Uses Ports and Messages to communicate between them.
  • Only support primitive data (though complex data can be passed around by Dictionary type)

When to use Isolate

  • Big JSON encoding/ decoding
  • Encryption
  • Image/ video processing

How to create an Isolate

  • Create 3 instances isolate, sendPort, receivePort
  • Registering an entry point to send and receive data
IMO, you wont use Isolate usually in most common applications. Mostly one Isolate but asynchronous is enough. This is doable through the async and await.

No comments:

Post a Comment