본문 바로가기
Flutter & Dart

Flutter & Dart - Isolates<in Dart>

by 방정맞은사람 2025. 1. 13.

Isolates in Dart (다트의 아이솔레이트)

Isolates란?

  • Isolate는 Dart에서 제공하는 경량 프로세스입니다.
  • Isolate는 독립적인 메모리 공간과 실행 흐름을 가지며, 병렬 처리를 가능하게 합니다.
  • 서로 간섭하지 않고 동작하며, 데이터를 주고받을 때 메시지 패싱(Message Passing)을 사용합니다.

Isolates의 특징

  1. 독립된 메모리 공간
    • Isolate는 서로 독립된 힙 메모리를 사용합니다.
    • 따라서 하나의 Isolate에서 발생한 문제(예: 메모리 누수)는 다른 Isolate에 영향을 미치지 않습니다.
  2. 병렬 처리
    • Isolate는 Dart의 싱글 스레드 모델을 보완하며, 동시에 여러 작업을 실행할 수 있습니다.
    • CPU 집약적인 작업을 메인 Isolate와 분리하여 앱의 응답성을 유지합니다.
  3. 메시지 기반 통신
    • Isolates는 서로 데이터를 공유할 수 없으므로, 메시지 패싱으로 통신합니다.
    • SendPort와 ReceivePort를 통해 메시지를 주고받습니다.

기본 사용법

1. 간단한 Isolate 생성 예제

import 'dart:async';
import 'dart:isolate';

void isolateEntryPoint(SendPort sendPort) {
  sendPort.send("Hello from Isolate!");
}

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

  receivePort.listen((message) {
    print(message); // 출력: Hello from Isolate!
    receivePort.close();
  });
}

2. CPU 집약적인 작업 분리

import 'dart:isolate';

void calculateSum(SendPort sendPort) {
  int sum = 0;
  for (int i = 0; i <= 1000000; i++) {
    sum += i;
  }
  sendPort.send(sum);
}

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

  receivePort.listen((message) {
    print('Sum: \\$message'); // 출력: Sum: 500000500000
    receivePort.close();
  });
}

3. Isolate와 두 방향 통신

import 'dart:isolate';

void isolateTask(SendPort mainSendPort) {
  final receivePort = ReceivePort();
  mainSendPort.send(receivePort.sendPort);

  receivePort.listen((message) {
    print('Isolate received: \\$message');
    if (message == "Ping") {
      mainSendPort.send("Pong");
    }
  });
}

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

  final sendPort = await receivePort.first as SendPort;
  sendPort.send("Ping");

  receivePort.listen((message) {
    print('Main received: \\$message'); // 출력: Main received: Pong
    receivePort.close();
  });
}

Isolates의 장점

  1. 효율적인 병렬 처리
    • CPU 집약적인 작업을 분리하여 메인 스레드의 부담을 줄임.
  2. 안정성
    • 메모리를 독립적으로 사용하므로, 한 Isolate의 문제로 인해 다른 Isolate가 영향을 받지 않음.
  3. 메시지 기반 통신
    • 명시적인 데이터 교환으로 상태 관리를 명확히 할 수 있음.

Isolates의 단점 및 주의사항

  1. 메시지 패싱의 오버헤드
    • 데이터를 공유하지 못하고 복사해서 전달하기 때문에, 대량의 데이터 교환은 성능에 영향을 미칠 수 있음.
  2. 복잡성 증가
    • Isolate 간 통신 코드가 추가되어 코드 복잡성이 증가.
  3. 제한된 사용 사례
    • Flutter UI 작업에는 적합하지 않으며, 주로 CPU 집약적인 작업에 사용.

Isolates와 Flutter의 관계

  1. UI와 Isolates
    • Flutter의 메인 Isolate는 UI를 담당하며, 다른 Isolate를 생성하여 무거운 작업을 처리.
  2. compute 함수
    • Flutter에서 Isolates를 쉽게 사용할 수 있는 유틸리티 함수.
    import 'package:flutter/foundation.dart';
    
    int calculateSum(int n) {
      int sum = 0;
      for (int i = 0; i <= n; i++) {
        sum += i;
      }
      return sum;
    }
    
    void main() async {
      final result = await compute(calculateSum, 1000000);
      print(result); // 출력: 500000500000
    }
    

결론

Isolates는 Dart의 병렬 처리 메커니즘으로, CPU 집약적인 작업을 메인 Isolate와 분리하여 앱의 성능을 향상시킬 수 있습니다. 적절히 활용하면 안정적이고 효율적인 코드를 작성할 수 있지만, 데이터 교환의 비용과 복잡성을 고려해야 합니다.