Sunday, February 2, 2014
Understanding Dart Futures and Isolates; their different way to work in time factor
Different cheme to use time factor to enhance programs effeciency.
Some clips gathered from dartlang.org pages:
Isolate api: https://api.dartlang.org/docs/channels/stable/latest/dart_isolate.html
Note: A Dart command-line app can run code in parallel by creating isolates. (Dart web apps can’t currently create additional isolates, but they can create workers.) Isolates don’t share memory; they’re like separate apps that communicate with each other by passing messages. With the exception of code that an app explicitly runs in additional isolates or workers, all of an app’s code runs in the app’s main isolate. For more information, see Use isolates or workers if necessary, later in this article.
How many isolates should you use? For compute-intensive tasks, you should generally use as many isolates as you expect to have CPUs available. Any additional isolates are just wasted if they’re purely computational. However, if the isolates perform asynchronous calls—to perform I/O, for example—then they won’t spend much time on the CPUs, so having more isolates than CPUs makes sense.
Dart replaces shared-memory threads with isolates
Concurrency is great, but shared-memory threads are error prone. Dart implements an isolate system for safer concurrent programming. Isolates are “isolated memory heaps” that can be spawned from a top-level function or URI. Isolates communicate by passing messages, which are copied before they are sent.
Future is here: https://api.dartlang.org/docs/channels/stable/latest/dart_async.html
Fun facts about Future:
The function that you pass into Future’s then() method executes immediately when the Future completes. (The function isn’t enqueued, it’s just called.)
If a Future is already complete before then() is invoked on it, then a task is added to the microtask queue, and that task executes the function passed into then().
The Future() and Future.delayed() constructors don’t complete immediately; they add an item to the event queue.
The Future.value() constructor completes in a microtask, similar to #2.
The Future.sync() constructor executes its function argument immediately and (unless that function returns a Future) completes in a microtask, similar to #2.
The event queue has entries from both Dart (futures, timers, isolate messages, and so on) and the system (user actions, I/O, and so on).
Summary: Futures are: Asked my frend to do it, he returns with result .
I started the process, I get a response in due course.
Are part of (BIG) async.api
Isolates are: Outside workers to enhance our work. And to bring safety.
Are in (small) dart:isolate library api
Command line... parallel
Concurrent programming, independent workers similar to threads
Futures and Isolates work with time factor differently, to enhance programs effectiveness.
Questions arise: to be continued....