Pakpoom Tiwakornkit
Pakpoom Tiwakornkit

Reputation: 2939

How does Dart/Flutter execute code concurrently even if it's single threaded?

I'm new to Dart/Flutter and have some Node.js background, I understand that Dart has some similarities with Node.js like event loop and single threaded. But I have a hard time understanding how Dart handles async for blocking I/O operation, especially internal I/O like file system and database operation.

For Node.js, when it handles blocking I/O, let's say read the content of a file. It puts that file system operation in the Thread Pool, Node.js then concurrently (not parallelly) runs the next line of code in the main thread while the file system operation keep running. When it finishes reading the file, it puts a read-file callback event in the Event Queue which will be dequeued by Event Loop and be executed in the main thread. The concept of Node.js is not hard to understand, but how about Dart?

As Dart has no Thread Pool or something similar to Node.js's, it's single threaded and the official site says it runs everything in the main thread, whether it find Future, async, or anything like that, it still runs in the main thread, when it finishes that operation, it then puts the callback in Event Queue waiting for being dequeued by Event Loop and executed in the main thread.

This leads to my confusion that Dart can still run the next line of code while file system operation (blocking I/O) is still running. Please have a look at this piece of code

File myFile = File("some-text-file");
myFile.readAsString().then((content) {
  print(content);
});
print("This is my next line");

output:

This is my next line
Lorem ipsum...

How is that possible by not blocking the I/O operation without utilizing Thread Pool or something similar to Node.js's? If it was Node.js, myFile.readAsString() will be delegated to Thread Pool for concurrency.

Or Dart indeed under the hood simply spawn a new Isolate for that blocking I/O operation?

Thank you in advance for all of your answers.

Upvotes: 1

Views: 2008

Answers (1)

jamesdlin
jamesdlin

Reputation: 90125

  1. Concurrency is not the same as parallelism. You don't need multiple threads to be concurrent.

  2. Each Dart isolate is single-threaded, but a Dart program can have multiple isolates.

  3. In most cases, an asynchronous operation ultimately executes some lower-level operation implemented outside of Dart (such as in the Dart VM/runtime or via an FFI binding) where they can spawn OS threads, spawn separate processes, or perhaps perform filesystem operations that performs asynchronous I/O. It depends the implementation of the asynchronous operation.

Upvotes: 1

Related Questions