TIL: Flutter | Dart (11) isolate (스레드 생성)- 221212

Lumpen·2022년 12월 11일
0

Dart

목록 보기
11/20

비동기 프로그래밍

future, stream 을 통해 비동기 프로그래밍을 지원한다
그 전에 isolate라는 다트의 구조부터 알아야 한다

isolate

격리하다는 뜻을 가졌다
isolate는 다트의 코드가 실행되는 공간이다
싱글 스레드를 가지고 있고 이벤트 루프를 통해 작업을 처리한다

기본 isolate인 main isolate는 런타임에 생성된다
비동기 프로그래밍을 지원하기 때문에 이벤트 루프에 의해 비동기 함수가 관리된다
main isolate가 무거운 작업을 할 경우 추가로 isolate를 생성할 수 있다
멀티 스레드가 되는 것이다
다만 기존의 언어에서의 스레드와는 다르다

기존의 언어에서 스레드는 서로 메모리를 공유하는 구조다
다트의 isolate 스레드는 각각의 자체적인 메모리를 가지고 있다
그러므로 메모리가 공유되지 않는다

두 isolate가 함께 작업하려면 message를 주고 받아야 한다
이 것은 불편하지만 멀티 스레드에서 주의해야하는 공유 자원에 대해 신경쓰지 않아도 된다

isolate 생성

spawn을 통해 isolate를 생성할 수 있다

import 'dart:isolate';

void main() {
	int counter = 0;
    
	ReceivePort mainReceivePort = new ReceivePort()// message 연동을 위한 port 생성
	
    mainReceivePort.listen((fooSendPort) => {
    	if (fooSendPort is SendPort) {
        	fooSendPort.send(counter++);
        } else {
        	print(fooSendPort);
        }
    });
     for (var i=0; i<5; i++) {
     	isolate.sqawn(foo, mainReceivePort.sendPort);
     }
}

foo (SendPort mainSendPort) {
	ReceivePort fooReceivePort = new ReceivePort();
    mainSendPort.send(fooReceivePort.sendPort);
    
    fooReceivePort.listen((msg) => {
    	mainSendPort.send('received: $msg');
    })
}

isolate는 스레드 경쟁에 의해 Isolate로 생성된 스레드는 순서가 보장되지 않는다

profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글