Junior — Middle
How can parallel execution of two threads be implemented in Dart?
sobes.tech AI
Answer from AI
In Dart, isolates are used for parallel execution of code because standard threads do not share memory and cannot operate in parallel within the same process.
To run two parallel threads, you need to create two isolates. Each isolate operates in its own memory space and communicates with others through messages.
Example of creating and running two isolates:
import 'dart:isolate';
void isolateEntry(SendPort sendPort) {
// Some work in the isolate
sendPort.send('Isolate has finished work');
}
void main() async {
ReceivePort receivePort1 = ReceivePort();
ReceivePort receivePort2 = ReceivePort();
await Isolate.spawn(isolateEntry, receivePort1.sendPort);
await Isolate.spawn(isolateEntry, receivePort2.sendPort);
receivePort1.listen((message) {
print('Message from first isolate: $message');
});
receivePort2.listen((message) {
print('Message from second isolate: $message');
});
}
Thus, for parallelism in Dart, you should use isolates rather than regular threads.