한국어
Qt
 

QML and Qt Quick QML과 코루틴(Coroutines)

makersweb 2020.11.03 22:25 조회 수 : 586

function * 선언 (함수 키워드 뒤에 별표)은 Generator 객체를 반환하는 generator 함수를 정의한다. 다음의 피보나치 예제는 generator와 QML을 사용하여 코루틴의 예를 보여준다.

import QtQuick 2.11
import QtQuick.Window 2.11
import QtQuick.Controls 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Fibonacci")

    property var fibonacci: function* () {
        yield "0: 0"
        yield "1: 1"
        var f0 = 1, f1 = 0, n = 2;
        while (true) {
            var next = f1 + f0;
            f0 = f1;
            f1 = next;
            yield (n++) + ": " + (f0 + f1);
        }
    }

    Row {
        anchors.fill: parent
        Button {
            id: button
            property var coroutine: fibonacci()
            width: parent.width / 2; height: parent.height
            text: coroutine.next().value
            onPressed: text = coroutine.next().value
        }


        Button {
            text: "Reset!"
            width: parent.width / 2; height: parent.height
            onPressed: {
                button.coroutine = fibonacci()
                button.text = button.coroutine.next().value
            }
        }
    }
}

 

코루틴 이란?

코루틴(coroutine)은 루틴의 일종으로서, 협동 루틴이라 할 수 있다(코루틴의 "Co"는 with 또는 togather를 뜻한다). 상호 연계 프로그램을 일컫는다고도 표현가능하다. 루틴과 서브 루틴은 서로 비대칭적인 관계이지만, 코루틴들은 완전히 대칭적인, 즉 서로가 서로를 호출하는 관계이다. 코루틴들에서는 무엇이 무엇의 서브루틴인지를 구분하는 것이 불가능하다. 코루틴 A와 B가 있다고 할 때, A를 프로그래밍 할 때는 B를 A의 서브루틴으로 생각한다. 그러나 B를 프로그래밍할 때는 A가 B의 서브루틴이라고 생각한다. 어떠한 코루틴이 발동될 때 마다 해당 코루틴은 이전에 자신의 실행이 마지막으로 중단되었던 지점 다음의 장소에서 실행을 재개한다. 출처: 위키백과