Sobes.tech
Junior — Middle

Is it possible to use multithreading in Dart for parallel task processing?

sobes.tech AI

Answer from AI

In Dart, multithreading is implemented through the "Isolates" mechanism — separate isolated threads with their own memory. They allow tasks to be executed in parallel but do not share memory directly, which prevents synchronization issues.

For parallel task processing, new Isolates are created, and they communicate via message passing.

Example of creating an Isolate:

import 'dart:isolate';

void task(SendPort sendPort) {
  // Some heavy task
  int result = 0;
  for (int i = 0; i < 1000000; i++) {
    result += i;
  }
  sendPort.send(result);
}

void main() async {
  ReceivePort receivePort = ReceivePort();
  await Isolate.spawn(task, receivePort.sendPort);

  receivePort.listen((message) {
    print('Result: $message');
    receivePort.close();
  });
}

Thus, in Dart, parallel processing can be achieved using Isolates, which is effective for CPU-intensive tasks.