<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://copyrat90.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://copyrat90.github.io/" rel="alternate" type="text/html" /><updated>2026-06-06T10:16:32+00:00</updated><id>https://copyrat90.github.io/feed.xml</id><title type="html">copyrat90::devlog</title><subtitle>copyrat90 의 개발일지</subtitle><entry><title type="html">(C++20) Coroutines (WIP)</title><link href="https://copyrat90.github.io/2025/10/10/cpp20-coroutines.html" rel="alternate" type="text/html" title="(C++20) Coroutines (WIP)" /><published>2025-10-10T00:00:00+00:00</published><updated>2025-10-13T08:33:00+00:00</updated><id>https://copyrat90.github.io/2025/10/10/cpp20-coroutines</id><content type="html" xml:base="https://copyrat90.github.io/2025/10/10/cpp20-coroutines.html"><![CDATA[<p>C++20 표준에 도입된 코루틴은 대체 뭐고, 어떻게 쓰는가?</p>

<p>본 글에서는, 우리가 일반적으로 쓰던 함수를 서브루틴<sub>Subroutines</sub>이라고 부르고, 이 글에서 다루고자 하는 대상을 코루틴<sub>Coroutines</sub>,<br />
둘 모두를 아우르거나 보다 포괄적으로 말할 때는 함수<sub>Function</sub>라는 표현을 쓰도록 하겠다.</p>

<p>내용은 <a href="https://lewissbaker.github.io">Lewis Baker - Asymmetric Transfer</a> 블로그 글들을 그대로 옮기거나 요약한 내용이다.</p>

<ul id="markdown-toc">
  <li><a href="#코루틴-이론" id="markdown-toc-코루틴-이론">코루틴 이론</a>    <ul>
      <li><a href="#활성-프레임activation-frame" id="markdown-toc-활성-프레임activation-frame">활성 프레임<sub>Activation frame</sub></a></li>
      <li><a href="#서브루틴의-호출call-명령" id="markdown-toc-서브루틴의-호출call-명령">서브루틴의 호출<sub>Call</sub> 명령</a></li>
      <li><a href="#서브루틴의-반환return-명령" id="markdown-toc-서브루틴의-반환return-명령">서브루틴의 반환<sub>Return</sub> 명령</a></li>
      <li><a href="#중단suspend-명령" id="markdown-toc-중단suspend-명령">중단<sub>Suspend</sub> 명령</a></li>
      <li><a href="#재개resume-명령" id="markdown-toc-재개resume-명령">재개<sub>Resume</sub> 명령</a></li>
      <li><a href="#파괴destroy-명령" id="markdown-toc-파괴destroy-명령">파괴<sub>Destroy</sub> 명령</a></li>
      <li><a href="#코루틴의-호출call-명령" id="markdown-toc-코루틴의-호출call-명령">코루틴의 호출<sub>Call</sub> 명령</a></li>
      <li><a href="#코루틴의-반환return-명령" id="markdown-toc-코루틴의-반환return-명령">코루틴의 반환<sub>Return</sub> 명령</a></li>
      <li><a href="#그림으로-이해하기" id="markdown-toc-그림으로-이해하기">그림으로 이해하기</a></li>
    </ul>
  </li>
  <li><a href="#co_await-연산자-이해하기" id="markdown-toc-co_await-연산자-이해하기"><code class="language-plaintext highlighter-rouge">co_await</code> 연산자 이해하기</a>    <ul>
      <li><a href="#코루틴-ts가-제공하는-것들" id="markdown-toc-코루틴-ts가-제공하는-것들">코루틴 TS가 제공하는 것들</a></li>
      <li><a href="#컴파일러---라이브러리-상호작용" id="markdown-toc-컴파일러---라이브러리-상호작용">컴파일러 &lt;-&gt; 라이브러리 상호작용</a></li>
      <li><a href="#awaiter와-awaitable-operator-co_await-설명" id="markdown-toc-awaiter와-awaitable-operator-co_await-설명">Awaiter와 Awaitable: <code class="language-plaintext highlighter-rouge">operator co_await</code> 설명</a>        <ul>
          <li><a href="#awaiter를-가져오기obtaining" id="markdown-toc-awaiter를-가져오기obtaining">Awaiter를 가져오기<sub>obtaining</sub></a></li>
          <li><a href="#awaiter를-대기하기awaiting" id="markdown-toc-awaiter를-대기하기awaiting">Awaiter를 대기하기<sub>awaiting</sub></a></li>
        </ul>
      </li>
      <li><a href="#코루틴-핸들coroutine-handles" id="markdown-toc-코루틴-핸들coroutine-handles">코루틴 핸들<sub>Coroutine Handles</sub></a></li>
      <li><a href="#동기화가-필요없는synchronisation-free-비동기-코드" id="markdown-toc-동기화가-필요없는synchronisation-free-비동기-코드">동기화가 필요없는<sub>Synchronisation-free</sub> 비동기 코드</a>        <ul>
          <li><a href="#stackful-코루틴과의-비교" id="markdown-toc-stackful-코루틴과의-비교">Stackful 코루틴과의 비교</a></li>
        </ul>
      </li>
      <li><a href="#메모리-할당-피하기" id="markdown-toc-메모리-할당-피하기">메모리 할당 피하기</a></li>
      <li><a href="#간단한-스레드-동기화-객체thread-synchronisation-primitive-예제" id="markdown-toc-간단한-스레드-동기화-객체thread-synchronisation-primitive-예제">간단한 스레드-동기화 객체<sub>thread-synchronisation primitive</sub> 예제</a></li>
    </ul>
  </li>
  <li><a href="#promise-타입-이해하기" id="markdown-toc-promise-타입-이해하기">promise 타입 이해하기</a>    <ul>
      <li><a href="#promise-객체" id="markdown-toc-promise-객체">Promise 객체</a>        <ul>
          <li><a href="#코루틴-프레임-할당" id="markdown-toc-코루틴-프레임-할당">코루틴 프레임 할당</a>            <ul>
              <li><a href="#코루틴-프레임-메모리-할당-커스터마이징" id="markdown-toc-코루틴-프레임-메모리-할당-커스터마이징">코루틴 프레임 메모리 할당 커스터마이징</a></li>
            </ul>
          </li>
          <li><a href="#코루틴-프레임으로-매개변수-복사" id="markdown-toc-코루틴-프레임으로-매개변수-복사">코루틴 프레임으로 매개변수 복사</a></li>
          <li><a href="#promise-객체-생성" id="markdown-toc-promise-객체-생성">promise 객체 생성</a></li>
          <li><a href="#반환-객체-얻어오기" id="markdown-toc-반환-객체-얻어오기">반환 객체 얻어오기</a></li>
          <li><a href="#최초-중단점the-initial-suspend-point" id="markdown-toc-최초-중단점the-initial-suspend-point">최초 중단점<sub>The initial-suspend point</sub></a></li>
          <li><a href="#호출자에게-반환" id="markdown-toc-호출자에게-반환">호출자에게 반환</a></li>
          <li><a href="#co_return으로-코루틴-반환" id="markdown-toc-co_return으로-코루틴-반환"><code class="language-plaintext highlighter-rouge">co_return</code>으로 코루틴 반환</a></li>
          <li><a href="#코루틴-몸체-바깥으로-전파된-예외-처리" id="markdown-toc-코루틴-몸체-바깥으로-전파된-예외-처리">코루틴 몸체 바깥으로 전파된 예외 처리</a></li>
          <li><a href="#최종-중단점the-final-suspend-point" id="markdown-toc-최종-중단점the-final-suspend-point">최종 중단점<sub>The final-suspend point</sub></a></li>
          <li><a href="#컴파일러는-promise-타입을-어떻게-선택하는가" id="markdown-toc-컴파일러는-promise-타입을-어떻게-선택하는가">컴파일러는 promise 타입을 어떻게 선택하는가</a></li>
          <li><a href="#특정-코루틴-활성-프레임을-구분하기identifying" id="markdown-toc-특정-코루틴-활성-프레임을-구분하기identifying">특정 코루틴 활성 프레임을 구분하기<sub>identifying</sub></a></li>
          <li><a href="#co_await의-동작-커스터마이징" id="markdown-toc-co_await의-동작-커스터마이징"><code class="language-plaintext highlighter-rouge">co_await</code>의 동작 커스터마이징</a></li>
          <li><a href="#co_yield의-동작-커스터마이징" id="markdown-toc-co_yield의-동작-커스터마이징"><code class="language-plaintext highlighter-rouge">co_yield</code>의 동작 커스터마이징</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="#symmetric-transfer-이해하기" id="markdown-toc-symmetric-transfer-이해하기">Symmetric Transfer 이해하기</a>    <ul>
      <li><a href="#task-코루틴-작동방식-배경-설명" id="markdown-toc-task-코루틴-작동방식-배경-설명">task 코루틴 작동방식 배경 설명</a></li>
      <li><a href="#task-구현-개요outline" id="markdown-toc-task-구현-개요outline"><code class="language-plaintext highlighter-rouge">task</code> 구현 개요<sub>Outline</sub></a></li>
      <li><a href="#taskpromise_type-구현하기" id="markdown-toc-taskpromise_type-구현하기"><code class="language-plaintext highlighter-rouge">task::promise_type</code> 구현하기</a></li>
      <li><a href="#taskoperator-co_await-구현하기" id="markdown-toc-taskoperator-co_await-구현하기"><code class="language-plaintext highlighter-rouge">task::operator co_await()</code> 구현하기</a></li>
      <li><a href="#스택-오버플로-문제" id="markdown-toc-스택-오버플로-문제">스택 오버플로 문제</a></li>
      <li><a href="#코루틴-ts-해결책" id="markdown-toc-코루틴-ts-해결책">코루틴 TS 해결책</a></li>
      <li><a href="#여전한-문제점" id="markdown-toc-여전한-문제점">여전한 문제점</a></li>
      <li><a href="#symmetric-transfer-입장" id="markdown-toc-symmetric-transfer-입장">“symmetric transfer” 입장!</a></li>
      <li><a href="#꼬리-호출tail-calls" id="markdown-toc-꼬리-호출tail-calls">꼬리 호출<sub>Tail-calls</sub></a></li>
      <li><a href="#task-재작성하기revisited" id="markdown-toc-task-재작성하기revisited"><code class="language-plaintext highlighter-rouge">task</code> 재작성하기<sub>revisited</sub></a>        <ul>
          <li><a href="#스택-시각화하기" id="markdown-toc-스택-시각화하기">스택 시각화하기</a></li>
        </ul>
      </li>
      <li><a href="#await_suspend의-보편적-형태the-universal-form로서의-symmetric-transfer" id="markdown-toc-await_suspend의-보편적-형태the-universal-form로서의-symmetric-transfer"><code class="language-plaintext highlighter-rouge">await_suspend</code>의 보편적 형태<sub>the Universal Form</sub>로서의 Symmetric Transfer</a>        <ul>
          <li><a href="#재귀를-종료하기terminating" id="markdown-toc-재귀를-종료하기terminating">재귀를 종료하기<sub>Terminating</sub></a></li>
          <li><a href="#다른-모습flavours의-await_suspend를-표현하기" id="markdown-toc-다른-모습flavours의-await_suspend를-표현하기">다른 모습<sub>flavours</sub>의 <code class="language-plaintext highlighter-rouge">await_suspend()</code>를 표현하기</a></li>
          <li><a href="#그럼-왜-3개의-모습flavours을-둬야-하나" id="markdown-toc-그럼-왜-3개의-모습flavours을-둬야-하나">그럼 왜 3개의 모습<sub>flavours</sub>을 둬야 하나?</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="#참고자료" id="markdown-toc-참고자료">참고자료</a></li>
</ul>

<h1 id="코루틴-이론">코루틴 이론</h1>

<p>우선 코루틴이 뭔지부터 정리해보자.</p>

<p>코루틴<sub>Coroutines</sub>은, 서브루틴<sub>Subroutines</sub>이 지원하는 호출<sub>Call</sub>과 반환<sub>Return</sub> 기능 뿐만 아니라,<br />
추가로 중단<sub>Suspend</sub>, 재개<sub>Resume</sub>, 파괴<sub>Destroy</sub>를 지원하는 좀 더 일반화된 함수라고 할 수 있다.</p>

<p>다시 말해, 코루틴은 자기가 원하는 시점에 함수를 일시 정지한 후, 호출자<sub>Caller</sub>(또는 재개자<sub>Resumer</sub>)에게 제어를 돌려주는<sub>transfers execution back</sub> 기능을 추가로 제공하는 함수이다.</p>

<h2 id="활성-프레임activation-frame">활성 프레임<sub>Activation frame</sub></h2>

<p>활성 프레임<sub>Activation frame</sub>이란, 함수의 현재 실행 상태를 저장하고 있는 메모리이다.<br />
대표적으로, 함수의 매개 변수<sub>parameters</sub>와 지역 변수<sub>local variables</sub>, 반환 주소<sub>return-address</sub>가 여기에 저장된다.</p>

<p>서브루틴에서는, 피호출자<sub>Callee</sub>가 호출자<sub>Caller</sub>에게 제어를 돌려주려면 함수를 끝내고 반환<sub>Return</sub>하는 방법 밖에 없다.<br />
이 말은, 피호출자<sub>Callee</sub> 활성 프레임의 생명 주기<sub>lifetime</sub>는 호출자<sub>Caller</sub>에 완벽히 종속된다는 의미이다.<br />
그래서 서브루틴의 활성 프레임은 LIFO 구조의 스택에 온전히 저장할 수 있다.</p>

<p>하지만 코루틴에서는, 피호출자가 자신의 실행을 일시 중단하고 호출자(또는 재개자)에게 제어를 돌려줄 수 있다.<br />
이 말은, 피호출자가 중단되더라도 그 활성 프레임은 살아있어야 한다는 의미이다. (경우에 따라 호출자가 반환된 이후까지 살아있을 수도 있음)<br />
그래서 코루틴의 활성 프레임은 스택에 온전히 저장될 수는 없다.</p>

<p>활성 프레임이 스택에 저장될 때, 이를 흔히 스택 프레임<sub>Stack frame</sub>이라고 부른다.<br />
스택 프레임을 할당/해제하는 방법은 간단하다. 그저 CPU 내 스택 포인터<sub>stack pointer</sub> 레지스터를 프레임 크기만큼 올리고/내리고 하면 된다.</p>

<p>코루틴의 경우, 활성 프레임은 두 부분으로 나뉘는데:</p>
<ol>
  <li><strong>스택 프레임</strong>: 재개 이후에는 재사용되지 않아서 중단 시 제거되어도 상관없는 부분</li>
  <li><strong>코루틴 프레임</strong>: 재개 이후에 재사용돼서 중단 시에도 살아있어야 하는 부분</li>
</ol>

<p>적어도 후자는 <code class="language-plaintext highlighter-rouge">operator new</code>로 할당된 공간에 저장된다.<br />
(테스트해봤는데 GCC 기준으로는 전자도 <code class="language-plaintext highlighter-rouge">operator new</code>로 할당된 공간에 몰아서 저장되는 것으로 보임)<br />
즉 기본적으로 스택에 저장되지 않는다는 것이며, 이를 stackless 코루틴이라고 부른다.</p>

<h2 id="서브루틴의-호출call-명령">서브루틴의 호출<sub>Call</sub> 명령</h2>

<p>함수가 다른 서브루틴을 호출할 때, 호출자는 자기 자신을 정지시킬 준비를 해야 한다.</p>

<p>우선 현재 CPU 레지스터의 값들을 나중에 복원하기 위해 메모리에 저장해야 한다.<br />
<a href="https://en.wikipedia.org/wiki/Calling_convention">호출 규약<sub>Calling convention</sub></a>에 따라 이걸 호출자가 할지, 피호출자가 할지가 달라진다.</p>

<p>그리고 호출자는 매개변수들을 새로운 활성 프레임에 저장해, 피호출자가 접근할 수 있도록 한다.<br />
또한 호출자는 자신이 재개될 주소를 새 활성 프레임에 저장하고, 제어를 피호출자 측으로 넘긴다.</p>

<h2 id="서브루틴의-반환return-명령">서브루틴의 반환<sub>Return</sub> 명령</h2>

<p>피호출자가 <code class="language-plaintext highlighter-rouge">return</code>문으로 반환되면, 피호출자는 우선 반환값<sub>return value</sub>를 호출자가 접근할 수 있는 곳에 저장한다.<br />
이는 호출자의 활성 프레임일 수도 있고, 피호출자의 활성 프레임일 수도 있다.<br />
(매개변수나 반환값은 두 활성 프레임의 경계에 걸쳐 있어서 어디라고 딱 집어 말하기 좀 애매한 구석이 있다.)</p>

<p>그리고 피호출자는 활성 프레임을 아래 과정을 통해 소멸<sub>destroy</sub>시킨다.</p>
<ul>
  <li>반환점<sub>return-point</sub> 기준으로 살아있는<sub>in-scope</sub> 지역 변수들 소멸<sub>destroy</sub></li>
  <li>매개변수들 소멸<sub>destroy</sub></li>
  <li>활성 프레임이 사용하는 메모리를 해제<sub>free</sub></li>
</ul>

<p>마지막으로, 아래 과정을 통해 호출자로 제어를 되돌려놓는다.</p>
<ul>
  <li>스택 포인터를 포함해 레지스터 값들을 복원
    <ul>
      <li>이를 통해 현재 활성 프레임이 호출자의 것으로 되돌아오게 됨</li>
    </ul>
  </li>
  <li>호출자의 재개점<sub>resume-point</sub>으로 점프<sub>jump</sub></li>
</ul>

<p><a href="https://en.wikipedia.org/wiki/Calling_convention">호출 규약<sub>Calling convention</sub></a>에 따라 반환 작업을 호출자, 피호출자가 나눠 할 수 있다.</p>

<h2 id="중단suspend-명령">중단<sub>Suspend</sub> 명령</h2>

<p>중단<sub>Suspend</sub> 명령은 코루틴의 중간 지점에서 실행을 중단하고 호출자(또는 재개자)에게 제어를 돌려주는 일을 한다.</p>

<p>코루틴의 몸체<sub>body</sub> 내부에 중단 지점<sub>suspend-points</sub>을 정의할 수 있다.<br />
C++20 코루틴에서는 <code class="language-plaintext highlighter-rouge">co_await</code>이나 <code class="language-plaintext highlighter-rouge">co_yield</code> 키워드를 사용한 지점이 중단 지점이 된다.</p>

<p>코루틴이 아무 중단 지점<sub>suspend-points</sub>에나 도달하면, 아래 과정을 통해 재개 가능토록 준비를 한다.</p>
<ul>
  <li>레지스터 값들을 코루틴 프레임에 저장</li>
  <li>어느 중단점<sub>suspend-point</sub>에서 멈췄는지를 나타내는 값 저장. 이를 통해:
    <ul>
      <li>어디서 재개<sub>Resume</sub>해야 할지를 알 수 있음</li>
      <li>어느 변수들이 살아있는지 알 수 있어, 파괴<sub>Destroy</sub> 명령에서 제거해야 하는 대상을 알 수 있음</li>
    </ul>
  </li>
</ul>

<p>코루틴이 재개 가능토록 준비가 되면, 코루틴은 ‘중단된’ 것으로 취급된다.</p>

<p>그 후, 코루틴은 호출자/재개자로 반환되기 전에 추가 로직을 수행할 수 있다.<br />
이 추가 로직에서는 코루틴 프레임의 핸들<sub>handle</sub>에 접근할 수 있는데, 이를 통해 코루틴을 재개/파괴할 수 있다.<br />
거기서 코루틴이 미래에 재개되도록 스케줄링<sub>schedule</sub>하면,
코루틴의 재개<sub>Resume</sub>가 자기 자신의 중단<sub>Suspend</sub>과 경쟁 상태<sub>race</sub>에 놓이는 것을 동기화<sub>synchronisation</sub> 없이 방지할 수 있다.</p>

<p>그 후, 코루틴은 즉시 실행을 재개할 것인지, 아니면 호출자/재개자에게 제어를 되돌려줄지를 선택할 수 있다.</p>

<p>호출자/재개자에게 제어가 되돌아간다면, 코루틴의 스택 프레임 부분은 스택에서 제거된다<sub>popped off the stack</sub>.</p>

<h2 id="재개resume-명령">재개<sub>Resume</sub> 명령</h2>

<p>재개<sub>Resume</sub> 명령은 현재 ‘중단’ 상태인 코루틴에 대해서만 쓸 수 있다.</p>

<p>어떤 함수가 코루틴을 재개하려면, 특정 코루틴 호출의 중간 부분으로 ‘호출’해 들어갈 수 있어야 한다.<br />
재개하고자 하는 특정한 호출<sub>particular invocation</sub>로 들어가기 위해,
재개자는 해당 호출의 중단<sub>Suspend</sub> 명령에서 제공됐던 코루틴 프레임 핸들을 가지고 <code class="language-plaintext highlighter-rouge">void resume()</code> 메서드를 호출한다.</p>

<p>일반 함수 호출과 마찬가지로, <code class="language-plaintext highlighter-rouge">resume()</code> 호출에서도 피호출자에게 제어를 넘기기 전에
새 스택 프레임을 할당하고 호출자의 반환 주소<sub>return-address</sub>를 스택 프레임에 저장해둔다.</p>

<p>하지만, 제어 흐름을 코루틴의 시작 부분으로 옮기는 대신, 코루틴이 마지막으로 실행 중이었던 위치로 옮긴다.<br />
코루틴 프레임에서 재개점<sub>resume-point</sub>을 불러와 거기로 점프하는 방식이다.</p>

<p>코루틴이 다음번에 중단되거나 끝까지 실행<sub>runs to completion</sub>되면 <code class="language-plaintext highlighter-rouge">resume()</code> 호출이 반환되고 호출자에게 제어가 되돌아간다.</p>

<h2 id="파괴destroy-명령">파괴<sub>Destroy</sub> 명령</h2>

<p>파괴<sub>Destroy</sub> 명령은 코루틴 재개 없이 코루틴 프레임을 제거<sub>destroys</sub>한다.<br />
현재 ‘중단’ 상태인 코루틴에 대해서만 쓸 수 있다.</p>

<p>파괴 명령은 재개 명령과 마찬가지로 새 스택 프레임을 할당하고 호출자의 반환 주소를 저장하여, 코루틴의 활성 프레임을 재활성화한다.<br />
하지만, 코루틴 몸체의 마지막 중단점으로 제어를 옮기는 대신,
별도의 코드 위치<sub>alternative code-path</sub>로 옮겨 중단점 내 지역 변수들을 정리하고 코루틴 프레임의 메모리를 해제<sub>free</sub>한다.</p>

<p>재개 명령과 비슷하게, 파괴 명령은 특정 호출의 중단<sub>Suspend</sub> 명령에서 제공됐던 코루틴 프레임 핸들을 가지고 <code class="language-plaintext highlighter-rouge">void destroy()</code> 메서드를 호출하여 이뤄진다.</p>

<h2 id="코루틴의-호출call-명령">코루틴의 호출<sub>Call</sub> 명령</h2>

<p>코루틴의 호출<sub>Call</sub> 명령은 서브루틴의 그것과 똑같다.<br />
사실, 호출자 측에서는 차이점이 아예 없다.</p>

<p>하지만, 제어가 호출자 측으로 되돌아오는 이유가 코루틴이 끝까지 실행<sub>runs to completion</sub>되어서일 수도 있고,
첫번째 중단점<sub>first suspend-point</sub>에서 중단되어서일 수도 있다는 점이 다르다.</p>

<p>코루틴을 호출할 때, 호출자는 새로운 스택 프레임을 할당하고, 매개변수와 반환 주소를 스택 프레임에 쓰고, 제어를 코루틴에게 넘긴다.<br />
이건 서브루틴 호출과 완전히 똑같다.</p>

<p>그 후 코루틴이 하는 첫번째 작업은 힙<sub>heap</sub>에 코루틴 프레임을 할당하고, 매개변수들을 스택 프레임 쪽에서 코루틴 프레임 쪽으로 복사/이동시키는 일이다.
복사/이동을 통해, 매개변수들은 첫번째 중단점 이후에도 살아남아 있을 수 있게 된다.</p>

<h2 id="코루틴의-반환return-명령">코루틴의 반환<sub>Return</sub> 명령</h2>

<p>코루틴의 반환<sub>Return</sub> 명령은 서브루틴과는 약간 다르다.</p>

<p>코루틴이 <code class="language-plaintext highlighter-rouge">co_return</code>문을 실행하면, 반환값을 어딘가에 저장하고(어디인지는 코루틴이 커스터마이징 할 수 있다),
범위 내<sub>in-scope</sub> 지역 변수들을 제거<sub>destructs</sub>한다.<br />
(하지만 매개변수는 제거하지 않는다.)</p>

<p>그 후, 코루틴은 호출자/재개자로 반환되기 전에 추가 로직을 수행할 수 있다.<br />
이 추가 로직은 마음대로 커스터마이징이 가능하다.<br />
예를 들어 반환값을 내보내기<sub>publish</sub> 위한 일을 수행할 수도, 결과를 기다리던 다른 코루틴을 재개할 수도 있다.</p>

<p>그 후, 코루틴은 아래 둘 중 하나의 명령을 수행한다:</p>
<ol>
  <li>중단<sub>Suspend</sub> 명령: 코루틴 프레임을 살려놓는다.</li>
  <li>파괴<sub>Destroy</sub> 명령: 코루틴 프레임을 제거<sub>destroy</sub>한다.</li>
</ol>

<p>그 후, 제어는 중단/파괴 명령의 동작 방식<sub>semantics</sub>에 따라 호출자/재개자에게 되돌아가며, 스택 프레임 부분을 제거한다.</p>

<p>반환<sub>Return</sub> 명령에 전달되는 반환값<sub>return-value</sub>은 호출<sub>Call</sub> 명령에서 반환받는 값과는 다르다는 점을 놓치지 말자.<br />
최초 호출 명령 이후, 한참 나중에야 재개된 코루틴이 반환 명령을 수행할 수도 있기 때문이다.</p>

<h2 id="그림으로-이해하기">그림으로 이해하기</h2>

<p>이 부분은 번역을 생략.<br />
<a href="https://lewissbaker.github.io/2017/09/25/coroutine-theory#an-illustration">원본 글의 An illustration 단락</a>을 참조하라.</p>

<h1 id="co_await-연산자-이해하기"><code class="language-plaintext highlighter-rouge">co_await</code> 연산자 이해하기</h1>

<p><code class="language-plaintext highlighter-rouge">co_await</code> 연산자의 작동 원리를 이해하면 코루틴이 어떻게 중단·재개되는지 그 베일을 벗기는 데<sub>demystify</sub> 도움이 될 수 있다.</p>

<p>하지만 우선 C++20 코루틴 TS<sub>기술 명세, Technical Specifications</sub>를 가볍게 살펴볼 필요가 있다.</p>

<h2 id="코루틴-ts가-제공하는-것들">코루틴 TS가 제공하는 것들</h2>

<ul>
  <li>새로운 언어 키워드: <a href="https://en.cppreference.com/w/cpp/keyword/co_await.html"><code class="language-plaintext highlighter-rouge">co_await</code></a>, <a href="https://en.cppreference.com/w/cpp/keyword/co_yield.html"><code class="language-plaintext highlighter-rouge">co_yield</code></a>, <a href="https://en.cppreference.com/w/cpp/keyword/co_return.html"><code class="language-plaintext highlighter-rouge">co_return</code></a></li>
  <li><a href="https://en.cppreference.com/w/cpp/coroutine.html"><code class="language-plaintext highlighter-rouge">&lt;coroutine&gt;</code> 헤더에 추가된 여러 타입들</a>
    <ul>
      <li><a href="https://en.cppreference.com/w/cpp/coroutine/coroutine_handle.html"><code class="language-plaintext highlighter-rouge">std::coroutine_handle</code></a></li>
      <li><a href="https://en.cppreference.com/w/cpp/coroutine/coroutine_traits.html"><code class="language-plaintext highlighter-rouge">std::coroutine_traits</code></a></li>
      <li><a href="https://en.cppreference.com/w/cpp/coroutine/suspend_always.html"><code class="language-plaintext highlighter-rouge">std::suspend_always</code></a></li>
      <li><a href="https://en.cppreference.com/w/cpp/coroutine/suspend_never.html"><code class="language-plaintext highlighter-rouge">std::suspend_never</code></a></li>
    </ul>
  </li>
  <li>라이브러리 작성자가 코루틴을 커스터마이징하는데 쓸 수 있는 일반적 메커니즘</li>
  <li>비동기<sub>asynchronous</sub> 코드 작성을 쉽게 만들어주는 언어 기능<sub>language facility</sub></li>
</ul>

<p>코루틴 TS가 제공하는 언어 설비<sub>facilities</sub>는 코루틴판 <em>저수준 어셈블리 언어</em>라고 생각할 수 있다.<br />
이 설비<sub>facilities</sub>는 직접 안전하게 쓰기는 어렵고, 어플리케이션 개발자들이 안전하게 쓸 수 있도록 라이브러리 작성자들에게 고수준 추상화 계층<sub>higher-level abstractions</sub>을 만들어 배포하라는 의도로 나온 것에 가깝다.</p>

<h2 id="컴파일러---라이브러리-상호작용">컴파일러 &lt;-&gt; 라이브러리 상호작용</h2>

<p>재미있게도, 코루틴 TS는 코루틴의 동작 방식<sub>semantics</sub>을 정의하지 않는다.<br />
호출자에게 전달할 값을 어떻게 생성해야 하는지 정의하지 않는다.<br />
<code class="language-plaintext highlighter-rouge">co_return</code>문에 전달된 반환값으로 무엇을 해야 하는지도, 코루틴 바깥으로 전파<sub>propagates</sub>된 예외를 어떻게 처리해야 하는지도 정의하지 않는다.<br />
코루틴이 어떤 스레드에서 재개되어야 하는지도 정의하지 않는다.</p>

<p>그 대신, 라이브러리 코드가 코루틴의 동작<sub>behaviour</sub>을 커스터마이징할 수 있도록 특정 인터페이스를 따르는 타입을 구현할 것을 요구한다.<br />
그러면 컴파일러가 라이브러리가 제공한 타입의 객체<sub>instance</sub>를 만들어, 그것의 메서드<sub>method</sub>를 호출하는 코드를 생성한다.<br />
이 방식<sub>approach</sub>은 라이브러리 작성자가 <code class="language-plaintext highlighter-rouge">iterator</code> 타입과 <code class="language-plaintext highlighter-rouge">begin()</code>/<code class="language-plaintext highlighter-rouge">end()</code>를 정의하여 범위 기반 for 반복문<sub>range-based for-loop</sub>을 커스터마이징 할 수 있는 것과 흡사하다.</p>

<p>코루틴 TS가 특정한 동작 방식을 강제하지 않는 덕분에 C++20 코루틴은 강력하다.<br />
이 덕에 라이브러리 작성자는 온갖 목적으로 서로 다른 다양한 코루틴을 정의할 수 있게 되었다.</p>

<p>예를 들어, 값 하나를 비동기적으로 생성하는<sub>produces a single value asynchronously</sub> 코루틴이나,<br />
여러 값을 게으르게 생성<sub>produces a sequence of values lazily</sub>하는 코루틴,<br />
<code class="language-plaintext highlighter-rouge">std::optional&lt;T&gt;</code> 값을 보고 <code class="language-plaintext highlighter-rouge">std::nullopt</code>이면 얼리 리턴<sub>early-exiting</sub>하여 제어 흐름<sub>control-flow</sub>을 단순화하는 코루틴 등을 정의할 수 있다.</p>

<p>코루틴 TS는 아래 2종류의 인터페이스를 정의한다:</p>
<ul>
  <li><strong>Promise</strong> 인터페이스</li>
  <li><strong>Awaitable</strong> 인터페이스</li>
</ul>

<p><strong>Promise</strong> 인터페이스는 코루틴 그 자체의 동작<sub>behaviour</sub>을 커스터마이징하는 메서드를 기술<sub>specifies</sub>한다.<br />
라이브러리 작성자는 코루틴이 호출될 때 무엇이 일어날지, 반환될 때 무엇이 일어날지 (일반적인 반환이나 처리되지 않은 예외),
해당 코루틴 내 <code class="language-plaintext highlighter-rouge">co_await</code>나 <code class="language-plaintext highlighter-rouge">co_yield</code> 표현식의 동작을 커스터마이징 할 수 있다.</p>

<p><strong>Awaitable</strong> 인터페이스는 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식의 동작 방식을 제어하는<sub>control the semantics of a <code class="language-plaintext highlighter-rouge">co_await</code> expression</sub> 메서드를 기술한다.<br />
값이 <code class="language-plaintext highlighter-rouge">co_await</code>되면, awaitable 객체에 대해 다음과 같은 일련의 호출을 하는 코드로 변환된다:</p>
<ul>
  <li>코루틴을 중단할지 말지를 판단</li>
  <li>중단된 후 실행되어 나중에 재개되도록 스케줄링하는 로직을 수행</li>
  <li>코루틴이 재개된 후 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식의 결과값을 생성하는 로직을 수행</li>
</ul>

<h2 id="awaiter와-awaitable-operator-co_await-설명">Awaiter와 Awaitable: <code class="language-plaintext highlighter-rouge">operator co_await</code> 설명</h2>

<p><code class="language-plaintext highlighter-rouge">co_await</code> 연산자는 새로운 단항 연산자로 하나의 값에 적용될 수 있다. (e.g. <code class="language-plaintext highlighter-rouge">co_await someValue</code>)</p>

<p><code class="language-plaintext highlighter-rouge">co_await</code> 연산자는 코루틴 내에서만 쓸 수 있다.
그런데 사실 이 설명은 다소 동어반복적<sub>tautology</sub>이다.
왜냐면 정의에 따르면 <code class="language-plaintext highlighter-rouge">co_await</code> 연산자를 사용한 함수 몸체는 코루틴으로 컴파일되기 때문이다.</p>

<p><code class="language-plaintext highlighter-rouge">co_await</code> 연산자를 지원하는 타입을 <strong>Awaitable</strong> 타입이라고 부른다.</p>

<p><code class="language-plaintext highlighter-rouge">co_await</code> 연산자가 어떤 타입에 적용될 수 있는지는 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식이 쓰인 문맥에 따라 다르다.<br />
코루틴에 쓰인 promise 타입의 <code class="language-plaintext highlighter-rouge">await_transform</code> 메서드가 <code class="language-plaintext highlighter-rouge">co_await</code>의 의미를 바꿔버릴 수 있기 때문이다.</p>

<p>필요한 경우 필자는 promise 타입에 <code class="language-plaintext highlighter-rouge">await_transform</code> 멤버가 없는 코루틴 문맥에서 <code class="language-plaintext highlighter-rouge">co_await</code> 연산자가 지원되는 경우 <strong>Normally Awaitable</strong>하다고 부른다.<br />
또한 필자는 promise 타입에 적절한 <code class="language-plaintext highlighter-rouge">await_transform</code>이 있는 특정 타입의 코루틴 문맥에서만 <code class="language-plaintext highlighter-rouge">co_await</code> 연산자가 지원되는 경우 <strong>Contextually Awaitable</strong>하다고 부른다.</p>

<p><strong>Awaiter</strong> 타입은 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식에서 호출되는 3개의 특별한 메서드를 구현하는 타입이다:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">await_ready</code></li>
  <li><code class="language-plaintext highlighter-rouge">await_suspend</code></li>
  <li><code class="language-plaintext highlighter-rouge">await_resume</code></li>
</ul>

<p>사실 ‘Awaiter’라는 용어는 C#의 <code class="language-plaintext highlighter-rouge">async</code> 키워드의 메커니즘에서 필자가 빌려온 것이다.<br />
C#의 <code class="language-plaintext highlighter-rouge">async</code> 키워드는 <code class="language-plaintext highlighter-rouge">GetAwaiter()</code> 메서드로 C++에서의 <strong>Awaiter</strong>와 기이하게 비스무리한<sub>eerily similar</sub> 인터페이스를 갖는 객체를 반환하도록 구현된다.<br />
C# awaiter가 궁금하다면 <a href="https://weblogs.asp.net/dixin/understanding-c-sharp-async-await-2-awaitable-awaiter-pattern">이 글</a>을 읽어보라.<br />
(역자 주: 그러고보니 이전에 <a href="/2025/03/23/csharp-custom-awaitable">C#에서 custom awaitable을 작성해본 적이 있는데</a>, C++ 코루틴과 꽤나 흡사한 측면이 있다.)</p>

<p>타입은 <strong>Awaitable</strong>이면서 동시에 <strong>Awaiter</strong>일 수 있다.</p>

<p>컴파일러가 <code class="language-plaintext highlighter-rouge">co_await &lt;expr&gt;</code> 표현식을 변환할 시, 관련 타입들에 의해 여러가지 방식으로 변환될 수 있다.</p>

<h3 id="awaiter를-가져오기obtaining">Awaiter를 가져오기<sub>obtaining</sub></h3>

<p>await되는 값에 대해 컴파일러가 제일 처음 하는 일은 그것의 <strong>Awaiter</strong> 객체를 가져오는<sub>obtain</sub> 일이다.<br />
awaiter 객체를 가져오기 위해 여러 단계를 거치는데, <a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4680.pdf">N4680</a>의 5.3.8(3)에 정리되어 있다.</p>

<p>await되려는 코루틴이 <code class="language-plaintext highlighter-rouge">P</code> 타입의 promise 객체를 가지고, <code class="language-plaintext highlighter-rouge">promise</code>는 그 객체의 좌측값 참조<sub>l-value reference</sub>라고 해보자.</p>

<p>promise 타입 <code class="language-plaintext highlighter-rouge">P</code>가 <code class="language-plaintext highlighter-rouge">await_transform</code> 멤버를 가지면 <code class="language-plaintext highlighter-rouge">&lt;expr&gt;</code>은 먼저 <code class="language-plaintext highlighter-rouge">promise.await_transform(&lt;expr&gt;)</code> 호출로 전달되어 <strong>Awaitable</strong> 값 <code class="language-plaintext highlighter-rouge">awaitable</code>을 가져온다.<br />
그렇지 않은, promise 타입에 <code class="language-plaintext highlighter-rouge">await_transform</code> 멤버가 없는 경우에는 <code class="language-plaintext highlighter-rouge">&lt;expr&gt;</code>을 있는 그대로 평가해 <strong>Awaitable</strong> 객체 <code class="language-plaintext highlighter-rouge">awaitable</code>로 사용한다.</p>

<p>그 후, <strong>Awaitable</strong> 객체 <code class="language-plaintext highlighter-rouge">awaitable</code>에 적용 가능한 <code class="language-plaintext highlighter-rouge">operator co_await()</code> 오버로드가 있는 경우, 이를 호출해 <strong>Awaiter</strong> 객체를 얻어온다.<br />
그렇지 않으면, <code class="language-plaintext highlighter-rouge">awaitable</code> 객체 그대로를 awaiter 객체로 사용한다.</p>

<p>위 규칙을 <code class="language-plaintext highlighter-rouge">get_awaitable()</code>과 <code class="language-plaintext highlighter-rouge">get_awaiter()</code>라는 함수의 형태로 나타낸다면, 이런 느낌일 것이다:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">P</span><span class="p">,</span> <span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span>
<span class="k">decltype</span><span class="p">(</span><span class="k">auto</span><span class="p">)</span> <span class="n">get_awaitable</span><span class="p">(</span><span class="n">P</span><span class="o">&amp;</span> <span class="n">promise</span><span class="p">,</span> <span class="n">T</span><span class="o">&amp;&amp;</span> <span class="n">expr</span><span class="p">)</span>
<span class="p">{</span>
  <span class="k">if</span> <span class="k">constexpr</span> <span class="p">(</span><span class="n">has_any_await_transform_member_v</span><span class="o">&lt;</span><span class="n">P</span><span class="o">&gt;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">promise</span><span class="p">.</span><span class="n">await_transform</span><span class="p">(</span><span class="k">static_cast</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&amp;&amp;&gt;</span><span class="p">(</span><span class="n">expr</span><span class="p">));</span>
  <span class="k">else</span>
    <span class="k">return</span> <span class="k">static_cast</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&amp;&amp;&gt;</span><span class="p">(</span><span class="n">expr</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">Awaitable</span><span class="p">&gt;</span>
<span class="k">decltype</span><span class="p">(</span><span class="k">auto</span><span class="p">)</span> <span class="n">get_awaiter</span><span class="p">(</span><span class="n">Awaitable</span><span class="o">&amp;&amp;</span> <span class="n">awaitable</span><span class="p">)</span>
<span class="p">{</span>
  <span class="k">if</span> <span class="k">constexpr</span> <span class="p">(</span><span class="n">has_member_operator_co_await_v</span><span class="o">&lt;</span><span class="n">Awaitable</span><span class="o">&gt;</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">static_cast</span><span class="o">&lt;</span><span class="n">Awaitable</span><span class="o">&amp;&amp;&gt;</span><span class="p">(</span><span class="n">awaitable</span><span class="p">).</span><span class="k">operator</span> <span class="k">co_await</span><span class="p">();</span>
  <span class="k">else</span> <span class="k">if</span> <span class="k">constexpr</span> <span class="p">(</span><span class="n">has_non_member_operator_co_await_v</span><span class="o">&lt;</span><span class="n">Awaitable</span><span class="o">&amp;&amp;&gt;</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">operator</span> <span class="k">co_await</span><span class="p">(</span><span class="k">static_cast</span><span class="o">&lt;</span><span class="n">Awaitable</span><span class="o">&amp;&amp;&gt;</span><span class="p">(</span><span class="n">awaitable</span><span class="p">));</span>
  <span class="k">else</span>
    <span class="k">return</span> <span class="k">static_cast</span><span class="o">&lt;</span><span class="n">Awaitable</span><span class="o">&amp;&amp;&gt;</span><span class="p">(</span><span class="n">awaitable</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="awaiter를-대기하기awaiting">Awaiter를 대기하기<sub>awaiting</sub></h3>

<p><code class="language-plaintext highlighter-rouge">&lt;expr&gt;</code> 결과를 <strong>Awaiter</strong>로 변환하는 로직을 위 함수들과 같이 캡슐화했다 치면
<code class="language-plaintext highlighter-rouge">co_await &lt;expr&gt;</code>의 의미<sub>semantics</sub>는 (대강) 이렇게 해석될 수 있다:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
  <span class="k">auto</span><span class="o">&amp;&amp;</span> <span class="n">value</span> <span class="o">=</span> <span class="o">&lt;</span><span class="n">expr</span><span class="o">&gt;</span><span class="p">;</span>
  <span class="k">auto</span><span class="o">&amp;&amp;</span> <span class="n">awaitable</span> <span class="o">=</span> <span class="n">get_awaitable</span><span class="p">(</span><span class="n">promise</span><span class="p">,</span> <span class="k">static_cast</span><span class="o">&lt;</span><span class="k">decltype</span><span class="p">(</span><span class="n">value</span><span class="p">)</span><span class="o">&gt;</span><span class="p">(</span><span class="n">value</span><span class="p">));</span>
  <span class="k">auto</span><span class="o">&amp;&amp;</span> <span class="n">awaiter</span> <span class="o">=</span> <span class="n">get_awaiter</span><span class="p">(</span><span class="k">static_cast</span><span class="o">&lt;</span><span class="k">decltype</span><span class="p">(</span><span class="n">awaitable</span><span class="p">)</span><span class="o">&gt;</span><span class="p">(</span><span class="n">awaitable</span><span class="p">));</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">awaiter</span><span class="p">.</span><span class="n">await_ready</span><span class="p">())</span>
  <span class="p">{</span>
    <span class="k">using</span> <span class="n">handle_t</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;</span><span class="n">P</span><span class="o">&gt;</span><span class="p">;</span>

    <span class="k">using</span> <span class="n">await_suspend_result_t</span> <span class="o">=</span>
      <span class="k">decltype</span><span class="p">(</span><span class="n">awaiter</span><span class="p">.</span><span class="n">await_suspend</span><span class="p">(</span><span class="n">handle_t</span><span class="o">::</span><span class="n">from_promise</span><span class="p">(</span><span class="n">promise</span><span class="p">)));</span>

    <span class="o">&lt;</span><span class="n">suspend</span><span class="o">-</span><span class="n">coroutine</span><span class="o">&gt;</span>

    <span class="k">if</span> <span class="k">constexpr</span> <span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">is_void_v</span><span class="o">&lt;</span><span class="n">await_suspend_result_t</span><span class="o">&gt;</span><span class="p">)</span>
    <span class="p">{</span>
      <span class="n">awaiter</span><span class="p">.</span><span class="n">await_suspend</span><span class="p">(</span><span class="n">handle_t</span><span class="o">::</span><span class="n">from_promise</span><span class="p">(</span><span class="n">promise</span><span class="p">));</span>
      <span class="o">&lt;</span><span class="k">return</span><span class="o">-</span><span class="n">to</span><span class="o">-</span><span class="n">caller</span><span class="o">-</span><span class="n">or</span><span class="o">-</span><span class="n">resumer</span><span class="o">&gt;</span>
    <span class="p">}</span>
    <span class="k">else</span>
    <span class="p">{</span>
      <span class="k">static_assert</span><span class="p">(</span>
         <span class="n">std</span><span class="o">::</span><span class="n">is_same_v</span><span class="o">&lt;</span><span class="n">await_suspend_result_t</span><span class="p">,</span> <span class="kt">bool</span><span class="o">&gt;</span><span class="p">,</span>
         <span class="s">"await_suspend() must return 'void' or 'bool'."</span><span class="p">);</span>

      <span class="k">if</span> <span class="p">(</span><span class="n">awaiter</span><span class="p">.</span><span class="n">await_suspend</span><span class="p">(</span><span class="n">handle_t</span><span class="o">::</span><span class="n">from_promise</span><span class="p">(</span><span class="n">promise</span><span class="p">)))</span>
      <span class="p">{</span>
        <span class="o">&lt;</span><span class="k">return</span><span class="o">-</span><span class="n">to</span><span class="o">-</span><span class="n">caller</span><span class="o">-</span><span class="n">or</span><span class="o">-</span><span class="n">resumer</span><span class="o">&gt;</span>
      <span class="p">}</span>
    <span class="p">}</span>

    <span class="o">&lt;</span><span class="n">resume</span><span class="o">-</span><span class="n">point</span><span class="o">&gt;</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="n">awaiter</span><span class="p">.</span><span class="n">await_resume</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>
<p>(역자 주: 위 코드와 아래 설명에는 <code class="language-plaintext highlighter-rouge">std::coroutine_handle</code>을 반환하는 버전의 <code class="language-plaintext highlighter-rouge">await_suspend()</code>가 빠져 있다.
해당 글이 작성된 2017년엔 코루틴 TS에 아직 symmetric transfer가 추가되기 전이어서 그런 듯하다. 이에 대한 내용은 한참 아래에서 다룬다.)</p>

<p><code class="language-plaintext highlighter-rouge">void</code>를 반환하는 버전의 <code class="language-plaintext highlighter-rouge">await_suspend()</code>의 경우 <code class="language-plaintext highlighter-rouge">await_suspend()</code>가 반환하면 무조건 코루틴의 호출자/재개자에게 제어를 돌려주고,<br />
<code class="language-plaintext highlighter-rouge">bool</code>을 반환하는 버전은 awaiter 객체가 조건부로 호출자/재개자에게 돌려주지 않고 코루틴을 즉시 재개하는 것을 허용한다.</p>

<p><code class="language-plaintext highlighter-rouge">bool</code>을 반환하는 버전의 <code class="language-plaintext highlighter-rouge">await_suspend()</code>가 유용한 경우가 있는데, 이를테면 awaiter가 시작한 비동기 명령<sub>async operation</sub>이 어떨 때는 동기적으로 완료될 수 있는 경우와 같은 상황에서 그러하다.<br />
동기적으로 완료되는 경우, <code class="language-plaintext highlighter-rouge">await_suspend()</code>가 <code class="language-plaintext highlighter-rouge">false</code>를 반환하여 코루틴이 즉시 재개되어 실행을 계속해야 한다고 명시할<sub>indicate</sub> 수 있다.</p>

<p>컴파일러는 <code class="language-plaintext highlighter-rouge">&lt;suspend-coroutine&gt;</code> 지점에 현재 코루틴의 상태를 저장하고 재개를 준비하는 코드를 생성한다.<br />
이는 레지스터 값들과 <code class="language-plaintext highlighter-rouge">&lt;resume-point&gt;</code>의 위치를 코루틴 프레임 메모리에 저장하는 과정을 포함한다.</p>

<p>현재 코루틴은 <code class="language-plaintext highlighter-rouge">&lt;suspend-coroutine&gt;</code> 명령이 완료되면 중단된 것으로 취급된다.<br />
중단된 코루틴을 우리측에서 처음으로 관찰할 수 있는 지점은 <code class="language-plaintext highlighter-rouge">await_suspend()</code> 호출 내부에서이다.<br />
코루틴이 중단되면 재개<sub>resumed</sub>되거나 파괴<sub>destroyed</sub>될 수 있다.</p>

<p>코루틴이 재개(혹은 파괴)되도록 스케줄링<sub>schedule</sub>하는 것은 <code class="language-plaintext highlighter-rouge">await_suspend()</code>의 책임이다.<br />
<code class="language-plaintext highlighter-rouge">await_suspend()</code>에서 <code class="language-plaintext highlighter-rouge">false</code>를 반환하는 것은 현재 스레드에서 코루틴을 즉시 재개하겠다고 스케줄링<sub>scheduling</sub>하는 것으로 취급된다<sub>counted as</sub>.</p>

<p><code class="language-plaintext highlighter-rouge">await_ready()</code> 메서드의 목적은 명령이 대기 없이 동기적으로 완료될 수 있는 경우 <code class="language-plaintext highlighter-rouge">&lt;suspend-coroutine&gt;</code>의 비용을 피하도록 하는 것이다.</p>

<p><code class="language-plaintext highlighter-rouge">&lt;return-to-caller-or-resumer&gt;</code> 지점에서 제어는 호출자나 재개자에게 되돌아가는데, 로컬 스택 프레임은 제거<sub>popping</sub>되지만 코루틴 프레임은 살아있다.</p>

<p>중단된 코루틴이 재개된다면, 그 때 수행 흐름<sub>execution</sub>은 <code class="language-plaintext highlighter-rouge">&lt;resume-point&gt;</code>로부터 재개된다.<br />
달리 말해, 결과를 얻기 위해 <code class="language-plaintext highlighter-rouge">await_resume()</code> 메서드가 호출되기 직전 시점부터 재개된다는 말이다.</p>

<p><code class="language-plaintext highlighter-rouge">await_resume()</code> 메서드의 반환값은 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식의 결과가 된다.<br />
<code class="language-plaintext highlighter-rouge">await_resume()</code> 메서드에서 예외를 던질 수도 있는데 그 경우 예외는 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식 바깥으로 전파된다.</p>

<p>예외가 <code class="language-plaintext highlighter-rouge">await_suspend()</code>의 바깥으로 전파되는 경우엔 코루틴이 <code class="language-plaintext highlighter-rouge">await_resume()</code> 호출 없이 자동으로 재개되고
예외는 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식 바깥으로 전파된다는 점을 유념하라.</p>

<h2 id="코루틴-핸들coroutine-handles">코루틴 핸들<sub>Coroutine Handles</sub></h2>

<p><code class="language-plaintext highlighter-rouge">co_await</code> 표현식의 <code class="language-plaintext highlighter-rouge">await_suspend()</code> 호출에서 매개변수로 <code class="language-plaintext highlighter-rouge">std::coroutine_handle&lt;P&gt;</code>가 전달된다는 것을 눈치챘을지도 모르겠다.</p>

<p>이 타입은 코루틴 프레임을 참조하는 소유권이 없는<sub>non-owning</sub> 핸들을 나타낸다.
이 핸들로 코루틴을 재개하거나 코루틴 프레임을 파괴할 수 있다.
또한 이 핸들을 통해 코루틴의 promise 객체에 접근할 수 있다.</p>

<p><code class="language-plaintext highlighter-rouge">std::coroutine_handle</code>은 (축약하면) 아래와 같은 인터페이스를 갖는다:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">namespace</span> <span class="n">std</span>
<span class="p">{</span>
  <span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">Promise</span><span class="p">&gt;</span>
  <span class="k">struct</span> <span class="nc">coroutine_handle</span><span class="p">;</span>

  <span class="k">template</span><span class="o">&lt;</span><span class="p">&gt;</span>
  <span class="k">struct</span> <span class="nc">coroutine_handle</span><span class="o">&lt;</span><span class="kt">void</span><span class="o">&gt;</span>
  <span class="p">{</span>
    <span class="kt">bool</span> <span class="n">done</span><span class="p">()</span> <span class="k">const</span><span class="p">;</span>

    <span class="kt">void</span> <span class="n">resume</span><span class="p">();</span>
    <span class="kt">void</span> <span class="n">destroy</span><span class="p">();</span>

    <span class="kt">void</span><span class="o">*</span> <span class="n">address</span><span class="p">()</span> <span class="k">const</span><span class="p">;</span>
    <span class="k">static</span> <span class="n">coroutine_handle</span> <span class="n">from_address</span><span class="p">(</span><span class="kt">void</span><span class="o">*</span> <span class="n">address</span><span class="p">);</span>
  <span class="p">};</span>

  <span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">Promise</span><span class="p">&gt;</span>
  <span class="k">struct</span> <span class="nc">coroutine_handle</span> <span class="o">:</span> <span class="n">coroutine_handle</span><span class="o">&lt;</span><span class="kt">void</span><span class="o">&gt;</span>
  <span class="p">{</span>
    <span class="n">Promise</span><span class="o">&amp;</span> <span class="n">promise</span><span class="p">()</span> <span class="k">const</span><span class="p">;</span>
    <span class="k">static</span> <span class="n">coroutine_handle</span> <span class="n">from_promise</span><span class="p">(</span><span class="n">Promise</span><span class="o">&amp;</span> <span class="n">promise</span><span class="p">);</span>

    <span class="k">static</span> <span class="n">coroutine_handle</span> <span class="n">from_address</span><span class="p">(</span><span class="kt">void</span><span class="o">*</span> <span class="n">address</span><span class="p">);</span>
  <span class="p">};</span>
<span class="p">}</span>
</code></pre></div></div>

<p><strong>Awaitable</strong> 타입을 구현할 때, <code class="language-plaintext highlighter-rouge">coroutine_handle</code>에서 핵심적으로 사용할 메서드는 <code class="language-plaintext highlighter-rouge">.resume()</code>일 것이다.
명령이 완료된 이후 대기하는<sub>awaiting</sub> 코루틴을 재개하고 싶을 때 호출하면 된다.<br />
<code class="language-plaintext highlighter-rouge">coroutine_handle</code>의 <code class="language-plaintext highlighter-rouge">.resume()</code>을 호출하면 중단된 코루틴이 <code class="language-plaintext highlighter-rouge">&lt;resume-point&gt;</code>로부터 재활성화된다.<br />
<code class="language-plaintext highlighter-rouge">.resume()</code> 호출은 다음 번 <code class="language-plaintext highlighter-rouge">&lt;return-to-caller-or-resumer&gt;</code>를 만나는 지점에서 반환될 것이다.</p>

<p><code class="language-plaintext highlighter-rouge">.destroy()</code> 메서드는 코루틴 프레임을 파괴시킨다.
스코프 내 변수들의 소멸자를 호출하고 코루틴 프레임이 사용하는 메모리를 해제한다.<br />
당신이 코루틴 promise 타입을 구현하는 라이브러리 작성자가 아니라면, 일반적으로는 <code class="language-plaintext highlighter-rouge">.destroy()</code>를 직접 호출할 필요는 없다. (사실 호출을 피해야 한다.)<br />
보통은, 코루틴 프레임은 코루틴이 반환하는 어떤 RAII 타입이 소유하도록 구현될 것이다.<br />
그러니 RAII 객체의 협력<sub>cooperation</sub> 없이 <code class="language-plaintext highlighter-rouge">.destroy()</code>를 호출하는 것은 이중 파괴 버그<sub>double-destruction bug</sub>를 야기할 것이다.</p>

<p><code class="language-plaintext highlighter-rouge">.promise()</code> 메서드는 코루틴 promise 객체의 참조를 반환한다.<br />
하지만 보통은, <code class="language-plaintext highlighter-rouge">.destroy()</code>와 마찬가지로, 당신이 promise 타입의 작성자일 때만 쓸모가 있다.<br />
코루틴의 promise 객체를 코루틴의 내부 구현 사항<sub>internal implementation detail</sub>으로 감추는 것을 고려하라.<br />
대부분의 <strong>Normally Awaitable</strong> 타입들에서 <code class="language-plaintext highlighter-rouge">await_suspend()</code> 메서드의 매개변수 타입으로 <code class="language-plaintext highlighter-rouge">coroutine_handle&lt;void&gt;</code>를 사용해야 한다. <code class="language-plaintext highlighter-rouge">coroutine_handle&lt;Promise&gt;</code> 대신.</p>

<p><code class="language-plaintext highlighter-rouge">coroutine_handle&lt;P&gt;::from_promise(P&amp; promise)</code> 함수는 코루틴 promise 객체의 참조로부터 코루틴 핸들을 재생성<sub>reconstructing</sub>하는 것을 가능케 한다.<br />
타입 <code class="language-plaintext highlighter-rouge">P</code>가 코루틴 프레임에 사용된 구체<sub>concrete</sub> promise 타입과 정확히 일치해야<sub>exactly matches</sub> 한다는 점을 유념하라.<br />
구체 promise 타입이 <code class="language-plaintext highlighter-rouge">Derived</code>인데 <code class="language-plaintext highlighter-rouge">coroutine_handle&lt;Base&gt;</code>를 생성하려고 하면 정의되지 않은 동작<sub>undefined behaviour</sub>이 될 수 있다.</p>

<p><code class="language-plaintext highlighter-rouge">.address()</code>/<code class="language-plaintext highlighter-rouge">from_address()</code> 함수들은 코루틴 핸들과 <code class="language-plaintext highlighter-rouge">void*</code> 포인터 사이의 변환을 가능케 한다.<br />
이건 ‘컨텍스트<sub>context</sub>’ 변수를 C-스타일 API에 넘기는 경우에 쓰라고 의도한 것이다.
그러니 어떤 상황에서는 <strong>Awaitable</strong> 타입을 구현하는 데 유용할 수도 있다.<br />
하지만, 필자 경험상 대부분의 경우 콜백 ‘컨텍스트’ 매개변수에 추가 정보를 넘겨야 했어서
보통 <code class="language-plaintext highlighter-rouge">coroutine_handle</code>을 구조체에 넣은 다음 그 구조체의 포인터를 ‘컨텍스트’ 매개변수로 넘겼지, <code class="language-plaintext highlighter-rouge">.address()</code> 반환값을 사용하진 않았다.</p>

<h2 id="동기화가-필요없는synchronisation-free-비동기-코드">동기화가 필요없는<sub>Synchronisation-free</sub> 비동기 코드</h2>

<p>(WIP)</p>

<h3 id="stackful-코루틴과의-비교">Stackful 코루틴과의 비교</h3>

<p>(WIP)</p>

<h2 id="메모리-할당-피하기">메모리 할당 피하기</h2>

<p>(WIP)</p>

<h2 id="간단한-스레드-동기화-객체thread-synchronisation-primitive-예제">간단한 스레드-동기화 객체<sub>thread-synchronisation primitive</sub> 예제</h2>

<p>이 부분은 번역을 생략.<br />
<a href="https://lewissbaker.github.io/2017/11/17/understanding-operator-co-await#an-example-implementing-a-simple-thread-synchronisation-primitive">원본 글의 An example: Implementing a simple thread-synchronisation primitive 단락</a>을 참조하라.</p>

<h1 id="promise-타입-이해하기">promise 타입 이해하기</h1>

<p>코루틴 TS는 <code class="language-plaintext highlighter-rouge">co_await</code>, <code class="language-plaintext highlighter-rouge">co_yield</code>, <code class="language-plaintext highlighter-rouge">co_return</code>의 3가지 키워드를 추가한다.<br />
이 코루틴 키워드 중 아무 것이나 함수 몸체에 사용하면 컴파일러는 그 함수를 서브루틴이 아닌 코루틴으로 컴파일한다.</p>

<p>컴파일러는 우리가 작성한 코드를 꽤 기계적인 변환<sub>fairly mechanical transformations</sub>을 거쳐
함수 내 특정 위치에서 실행을 중단, 나중에 재개할 수 있는 상태 기계<sub>state-machine</sub>로 바꾸어놓는다.</p>

<p>코루틴 TS에서 도입한 2번째 인터페이스인 <strong>Promise</strong> 인터페이스는 이 코드 변환에 중요한 역할을 한다.</p>

<p><strong>Promise</strong> 인터페이스는 코루틴 그 자체의 동작<sub>behaviour</sub>을 커스터마이징하는 메서드를 기술<sub>specifies</sub>한다.<br />
라이브러리 작성자는 코루틴이 호출될 때 무엇이 일어날지, 반환될 때 무엇이 일어날지 (일반적인 반환이나 처리되지 않은 예외),
해당 코루틴 내 <code class="language-plaintext highlighter-rouge">co_await</code>나 <code class="language-plaintext highlighter-rouge">co_yield</code> 표현식의 동작을 커스터마이징 할 수 있다.</p>

<h2 id="promise-객체">Promise 객체</h2>

<p><strong>Promise</strong> 객체는 코루틴 실행 중 특정 지점에 호출되는 메서드들을 구현함으로써 코루틴 그 자체의 동작을 정의하고 제어한다.</p>

<blockquote>
  <p>계속하기에 앞서, “promise”가 무엇인지에 관한 모든 선입견을 내려놓기를 바란다.<br />
비록 어떤 용례에서는 코루틴 promise 객체가 실제로 <code class="language-plaintext highlighter-rouge">std::future</code> 짝<sub>pair</sub>의 <code class="language-plaintext highlighter-rouge">std::promise</code> 부분과 비슷한 역할을 하기도 하지만,
다른 용례에서는 이 유사점이 과장되는 측면이 있다<sub>the analogy is somewhat stretched</sub>.<br />
코루틴의 promise 객체를 코루틴의 동작을 제어하고 그 상태를 추적하는 “코루틴 상태 컨트롤러<sub>coroutine state controller</sub>” 객체라고 여기는 편이 더 쉬울 수도 있다.</p>
</blockquote>

<p>promise 객체의 인스턴스<sub>instance</sub>는 코루틴 함수가 호출될 때 코루틴 프레임 내부에 생성된다.</p>

<p>컴파일러는 코루틴 실행 중 중요한 지점들에 promise 객체의 특정 메서드들을 호출하는 코드를 생성한다.</p>

<p>아래 예제들에서, 특정 코루틴 호출의 코루틴 프레임 내에 생성된 promise 객체를 <code class="language-plaintext highlighter-rouge">promise</code>라고 가정하겠다.</p>

<p><code class="language-plaintext highlighter-rouge">&lt;body-statements&gt;</code>라는 몸체를 가지는 코루틴 함수를 작성했고, 그 안에 코루틴 키워드(<code class="language-plaintext highlighter-rouge">co_return</code>, <code class="language-plaintext highlighter-rouge">co_await</code>, <code class="language-plaintext highlighter-rouge">co_yield</code>)가 존재한다면
코루틴 몸체는 (대강) 아래와 같은 코드로 변환된다:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
  <span class="k">co_await</span> <span class="n">promise</span><span class="p">.</span><span class="n">initial_suspend</span><span class="p">();</span>
  <span class="k">try</span>
  <span class="p">{</span>
    <span class="o">&lt;</span><span class="n">body</span><span class="o">-</span><span class="n">statements</span><span class="o">&gt;</span>
  <span class="p">}</span>
  <span class="k">catch</span> <span class="p">(...)</span>
  <span class="p">{</span>
    <span class="n">promise</span><span class="p">.</span><span class="n">unhandled_exception</span><span class="p">();</span>
  <span class="p">}</span>
<span class="nl">FinalSuspend:</span>
  <span class="k">co_await</span> <span class="n">promise</span><span class="p">.</span><span class="n">final_suspend</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>코루틴 함수가 호출될 때, 코루틴 몸체의 코드를 실행하기에 앞서 수행되는 여러 단계가 있는데, 이는 일반적인 서브루틴의 동작과는 약간 다르다.</p>

<p>이 단계를 요약하면 다음과 같다 (각 단계는 아래에서 더 상세히 다룬다).</p>
<ol>
  <li><code class="language-plaintext highlighter-rouge">operator new</code>를 이용해 코루틴 프레임을 할당한다 (선택).</li>
  <li>함수 매개변수를 코루틴 프레임에 복사한다.
    <ul>
      <li>값 매개변수는 복사/이동되고, 참조는 참조로 남는다.
        <ul>
          <li>고로 참조하는 객체의 수명이 끝났다면 참조는 dangling이 된다.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">P</code> 타입 promise 객체의 생성자를 호출한다.
    <ul>
      <li>promise 타입이 모든 코루틴 매개변수를 받는 생성자를 갖고 있다면, 복사가 완료된 코루틴 실인자<sub>arguments</sub>들로 그 생성자를 호출한다.</li>
      <li>그렇지 않다면, 기본 생성자가 호출된다.</li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">promise.get_return_object()</code> 메서드를 호출해 그 결과를 지역 변수로 들고 있는다. 이는 코루틴이 처음 중단될 때 호출자에게 반환된다.
    <ul>
      <li>이 단계를 포함, 그 전에 예외가 던져진다면 예외는 호출자에게 전파되지, promise에 저장되지 않는다.</li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">promise.initial_suspend()</code> 메서드를 호출해 그 결과를 <code class="language-plaintext highlighter-rouge">co_await</code>한다.
    <ul>
      <li>Promise 타입은 흔히 <code class="language-plaintext highlighter-rouge">std::suspend_always</code>를 반환해 게으른 시작<sub>lazily-started</sub>을 하거나, <code class="language-plaintext highlighter-rouge">std::suspend_never</code>로 즉시 시작<sub>eagerly-started</sub>한다.</li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">co_await promise.initial_suspend()</code> 표현식이 (즉시든 비동기든) 재개되면, 당신이 작성한 코루틴 몸체의 수행을 시작한다.</li>
</ol>

<p>(역자 주: <a href="https://en.cppreference.com/w/cpp/language/coroutines.html#Execution">cppreference 코루틴 문서</a>에서는
코루틴 프레임<sub>coroutine frame</sub> 대신 코루틴 상태<sub>coroutine state</sub>라는 표현을 사용한다.<br />
또한 코루틴 상태의 할당/해제가 선택사항이라는 언급이 없는데, 확정된 표준은 선택권을 주지 않는 것일지도 모르겠다.<br />
제대로 확인하려면 확정된 표준 문서를 읽어봐야하겠는데 귀찮은 관계로 생략…)</p>

<p><code class="language-plaintext highlighter-rouge">co_return</code>문에 도달하면 아래 동작이 수행된다:</p>
<ol>
  <li><code class="language-plaintext highlighter-rouge">promise.return_void()</code> 또는 <code class="language-plaintext highlighter-rouge">promise.return_value(&lt;expr&gt;)</code>를 수행한다.
    <ul>
      <li><code class="language-plaintext highlighter-rouge">&lt;expr&gt;</code>이 <code class="language-plaintext highlighter-rouge">void</code>로 평가되면 전자를 수행, 아니면 후자</li>
    </ul>
  </li>
  <li>automatic storage duration 생명주기를 갖는 모든 변수를 생성된 것의 역순으로 소멸시킨다.</li>
  <li><code class="language-plaintext highlighter-rouge">promise.final_suspend()</code>를 호출해 그 결과를 <code class="language-plaintext highlighter-rouge">co_await</code>한다.</li>
</ol>

<p>그 대신, 코루틴이 처리되지 않는 예외로 인해 <code class="language-plaintext highlighter-rouge">&lt;body-statements&gt;</code>를 빠져나간다면:</p>
<ol>
  <li>예외를 잡아 catch-block 내에서 <code class="language-plaintext highlighter-rouge">promise.unhandled_exception()</code>을 호출한다.</li>
  <li><code class="language-plaintext highlighter-rouge">promise.final_suspend()</code>를 호출해 그 결과를 <code class="language-plaintext highlighter-rouge">co_await</code>한다.
    <ul>
      <li>예를 들어 continuation을 재개하거나 결과를 내보내기<sub>publish</sub> 위해 쓰일 수 있다.</li>
      <li>이 시점 이후로 코루틴을 재개하면 undefined behavior이다.</li>
    </ul>
  </li>
</ol>

<p><code class="language-plaintext highlighter-rouge">co_return</code>이든, 처리되지 않은 예외이든, 핸들을 통해 파괴되든 간에, 코루틴 상태가 파괴되면 다음 동작을 수행한다:</p>
<ol>
  <li>promise 객체의 소멸자를 호출한다.</li>
  <li>함수 매개변수 복사본들의 소멸자를 호출한다.</li>
  <li>코루틴 상태가 사용하던 메모리를 <code class="language-plaintext highlighter-rouge">operator delete</code>로 해제한다 (선택).</li>
  <li>호출자/재개자에게 제어를 돌려준다.</li>
</ol>

<p>수행 흐름<sub>execution</sub>이 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식 내의 <code class="language-plaintext highlighter-rouge">&lt;return-to-caller-or-resumer&gt;</code> 지점에 처음 도달하면,
또는 코루틴이 <code class="language-plaintext highlighter-rouge">&lt;return-to-caller-or-resumer&gt;</code>를 한번도 만나지 않고 끝까지 수행되면,
코루틴은 중단되거나 파괴되고, 이전에 <code class="language-plaintext highlighter-rouge">promise.get_return_object()</code> 호출로 반환됐던 반환 객체가 코루틴의 호출자에게 반환된다.</p>

<h3 id="코루틴-프레임-할당">코루틴 프레임 할당</h3>

<p>(WIP)</p>

<h4 id="코루틴-프레임-메모리-할당-커스터마이징">코루틴 프레임 메모리 할당 커스터마이징</h4>

<p>(WIP)</p>

<h3 id="코루틴-프레임으로-매개변수-복사">코루틴 프레임으로 매개변수 복사</h3>

<p>(WIP)</p>

<h3 id="promise-객체-생성">promise 객체 생성</h3>

<p>(WIP)</p>

<h3 id="반환-객체-얻어오기">반환 객체 얻어오기</h3>

<p>(WIP)</p>

<h3 id="최초-중단점the-initial-suspend-point">최초 중단점<sub>The initial-suspend point</sub></h3>

<p>(WIP)</p>

<h3 id="호출자에게-반환">호출자에게 반환</h3>

<p>(WIP)</p>

<h3 id="co_return으로-코루틴-반환"><code class="language-plaintext highlighter-rouge">co_return</code>으로 코루틴 반환</h3>

<p>(WIP)</p>

<h3 id="코루틴-몸체-바깥으로-전파된-예외-처리">코루틴 몸체 바깥으로 전파된 예외 처리</h3>

<p>(WIP)</p>

<h3 id="최종-중단점the-final-suspend-point">최종 중단점<sub>The final-suspend point</sub></h3>

<p>코루틴 몸체의 사용자가 정의한 부분의 수행이 끝나고 결과가 <code class="language-plaintext highlighter-rouge">return_void()</code>, <code class="language-plaintext highlighter-rouge">return_value()</code>, <code class="language-plaintext highlighter-rouge">unhandled_exception()</code> 호출로 잡히고<sub>captured</sub> 모든 지역 변수가 소멸된 후에,
코루틴은 호출자/재개자로 반환되기 전에 추가 로직을 수행할 수 있다.</p>

<p>코루틴은 <code class="language-plaintext highlighter-rouge">co_await promise.final_suspend();</code> 문을 수행한다.</p>

<p>이 덕에 코루틴은 결과를 내보내거나<sub>publish</sub>, 완료를 통지하거나<sub>signalling completion</sub>, continuation을 재개하는 등의 로직을 수행할 수 있다.<br />
또한 이 덕에 원한다면 코루틴이 끝까지 실행되어 코루틴 프레임이 파괴되기 전에 코루틴을 즉시 중단시킬 수 있다.</p>

<p><code class="language-plaintext highlighter-rouge">final_suspend</code> 시점에서 중단된 코루틴을 <code class="language-plaintext highlighter-rouge">resume()</code>하는 것은 정의되지 않은 동작<sub>undefined behaviour</sub>이라는 점을 유념하라.<br />
여기서 중단된 코루틴에 할 수 있는 것은 <code class="language-plaintext highlighter-rouge">destroy()</code> 뿐이다.</p>

<p>이 제한사항의 이유<sub>rationale</sub>는, Gor Nishanov에 따르면,
표현돼야 하는 중단 상태와 필요한 분기의 개수를 줄임으로써 컴파일러가 최적화할 여지가 많아지는 효과가 있기 때문이다.</p>

<p>코루틴이 <code class="language-plaintext highlighter-rouge">final_suspend</code> 지점에서 중단되지 않는 것이 허용되기는 하지만, 가능하면 <strong>당신 코루틴이 <code class="language-plaintext highlighter-rouge">final_suspend</code>에서 중단되도록 코루틴을 구조화하는 것이 추천된다</strong>는 것을 유념하자.<br />
왜냐하면 이렇게 하면 <code class="language-plaintext highlighter-rouge">.destroy()</code> 호출을 코루틴 바깥에서 하는 것이 강제되어 (보통은 어떤 RAII 소멸자에서 담당할 것이다)
컴파일러가 코루틴 프레임의 생명 주기가 호출자에게 종속되는지<sub>nested</sub> 판단하기가 훨씬 용이해지기 때문이다.<br />
그렇게 되면 컴파일러가 코루틴 프레임의 메모리 할당을 생략<sub>elide</sub>할 가능성이 훨씬 높아진다.</p>

<h3 id="컴파일러는-promise-타입을-어떻게-선택하는가">컴파일러는 promise 타입을 어떻게 선택하는가</h3>

<p>(WIP)</p>

<h3 id="특정-코루틴-활성-프레임을-구분하기identifying">특정 코루틴 활성 프레임을 구분하기<sub>identifying</sub></h3>

<p>(WIP)</p>

<h3 id="co_await의-동작-커스터마이징"><code class="language-plaintext highlighter-rouge">co_await</code>의 동작 커스터마이징</h3>

<p>promise 타입은 원한다면 코루틴 몸체에 있는 모든 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식의 동작을 커스터마이징 할 수 있다.</p>

<p>promise 타입에 <code class="language-plaintext highlighter-rouge">await_transform()</code>이라는 이름의 메서드를 정의하기만 하면,
컴파일러는 코루틴 몸체의 모든 <code class="language-plaintext highlighter-rouge">co_await &lt;expr&gt;</code>을 <code class="language-plaintext highlighter-rouge">co_await promise.await_transform(&lt;expr&gt;)</code>로 바꿔놓는다.</p>

<p>여기엔 여러 중요하고 강력한 용도들이 있다:</p>

<p><strong>1. Normally Awaitable하지 않은 타입을 awaiting할 수 있게 된다.</strong></p>

<p>예를 들어, <code class="language-plaintext highlighter-rouge">std::optional&lt;T&gt;</code>를 반환하는 코루틴의 promise 타입은,
<code class="language-plaintext highlighter-rouge">std::optional&lt;U&gt;</code>를 받아 <code class="language-plaintext highlighter-rouge">U</code>타입 값을 반환하거나 <code class="language-plaintext highlighter-rouge">std::nullopt</code>의 경우엔 코루틴을 중단시키는
<code class="language-plaintext highlighter-rouge">await_transform()</code> 오버로드를 제공할 수 있다.</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span>
<span class="k">class</span> <span class="nc">optional_promise</span>
<span class="p">{</span>
  <span class="p">...</span>

  <span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">U</span><span class="p">&gt;</span>
  <span class="k">auto</span> <span class="n">await_transform</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">optional</span><span class="o">&lt;</span><span class="n">U</span><span class="o">&gt;&amp;</span> <span class="n">value</span><span class="p">)</span>
  <span class="p">{</span>
    <span class="k">class</span> <span class="nc">awaiter</span>
    <span class="p">{</span>
      <span class="n">std</span><span class="o">::</span><span class="n">optional</span><span class="o">&lt;</span><span class="n">U</span><span class="o">&gt;&amp;</span> <span class="n">value</span><span class="p">;</span>
    <span class="nl">public:</span>
      <span class="k">explicit</span> <span class="n">awaiter</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">optional</span><span class="o">&lt;</span><span class="n">U</span><span class="o">&gt;&amp;</span> <span class="n">x</span><span class="p">)</span> <span class="k">noexcept</span> <span class="o">:</span> <span class="n">value</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="p">{}</span>
      <span class="kt">bool</span> <span class="n">await_ready</span><span class="p">()</span> <span class="k">noexcept</span> <span class="p">{</span> <span class="k">return</span> <span class="n">value</span><span class="p">.</span><span class="n">has_value</span><span class="p">();</span> <span class="p">}</span>
      <span class="kt">void</span> <span class="n">await_suspend</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;&gt;</span><span class="p">)</span> <span class="k">noexcept</span> <span class="p">{}</span>
      <span class="n">U</span><span class="o">&amp;</span> <span class="n">await_resume</span><span class="p">()</span> <span class="k">noexcept</span> <span class="p">{</span> <span class="k">return</span> <span class="o">*</span><span class="n">value</span><span class="p">;</span> <span class="p">}</span>
    <span class="p">};</span>
    <span class="k">return</span> <span class="n">awaiter</span><span class="p">{</span> <span class="n">value</span> <span class="p">};</span>
  <span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>

<p><strong>2. 특정 타입의 <code class="language-plaintext highlighter-rouge">await_transform</code> 오버로드를 delete로 선언하여 그 타입들이 awaiting되는 걸 막을 수 있다.</strong></p>

<p>예를 들어, <code class="language-plaintext highlighter-rouge">std::generator&lt;T&gt;</code>의 promise 타입은 아무 타입이나 받을 수 있는 <code class="language-plaintext highlighter-rouge">await_transform()</code> 템플릿 멤버 함수를 delete로 선언할 수 있다.<br />
이렇게 하면 코루틴 내에서 <code class="language-plaintext highlighter-rouge">co_await</code>의 사용을 막는 효과가 있다.</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span>
<span class="k">class</span> <span class="nc">generator_promise</span>
<span class="p">{</span>
  <span class="p">...</span>

  <span class="c1">// 이 코루틴 타입에 대해서 co_await 사용을 방지한다.</span>
  <span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">U</span><span class="p">&gt;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">suspend_never</span> <span class="n">await_transform</span><span class="p">(</span><span class="n">U</span><span class="o">&amp;&amp;</span><span class="p">)</span> <span class="o">=</span> <span class="k">delete</span><span class="p">;</span>

<span class="p">};</span>
</code></pre></div></div>

<p><strong>3. Normally Awaitable한 값의 동작을 변경<sub>adapt and change</sub>할 수 있다.</strong></p>

<p>예를 들어, 모든 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식이 특정 executor에서 재개되도록 하는 종류의 코루틴을 정의할 수 있다.
이는 awaitable을 <code class="language-plaintext highlighter-rouge">resume_on()</code> 연산자로 감싸는<sub>wrapping</sub> 식으로 구현될 수 있다 (<code class="language-plaintext highlighter-rouge">cppcoro::resume_on()</code>을 보라).</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">,</span> <span class="k">typename</span> <span class="nc">Executor</span><span class="p">&gt;</span>
<span class="k">class</span> <span class="nc">executor_task_promise</span>
<span class="p">{</span>
  <span class="n">Executor</span> <span class="n">executor</span><span class="p">;</span>

<span class="nl">public:</span>

  <span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">Awaitable</span><span class="p">&gt;</span>
  <span class="k">auto</span> <span class="n">await_transform</span><span class="p">(</span><span class="n">Awaitable</span><span class="o">&amp;&amp;</span> <span class="n">awaitable</span><span class="p">)</span>
  <span class="p">{</span>
    <span class="k">using</span> <span class="n">cppcoro</span><span class="o">::</span><span class="n">resume_on</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">resume_on</span><span class="p">(</span><span class="k">this</span><span class="o">-&gt;</span><span class="n">executor</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">forward</span><span class="o">&lt;</span><span class="n">Awaitable</span><span class="o">&gt;</span><span class="p">(</span><span class="n">awaitable</span><span class="p">));</span>
  <span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>

<p>마지막으로 <code class="language-plaintext highlighter-rouge">await_transform()</code>에 대해 첨언하면, promise 타입에 대해 <code class="language-plaintext highlighter-rouge">await_transform()</code> 멤버를 <em>하나라도</em> 정의하는 순간
컴파일러는 <em>모든</em> <code class="language-plaintext highlighter-rouge">co_await</code> 표현식을 <code class="language-plaintext highlighter-rouge">promise.await_transform()</code> 호출로 바꿔놓는다는 점을 유념하는 게 중요하다.<br />
이 말은 일부 타입에 대해서만 <code class="language-plaintext highlighter-rouge">co_await</code>의 동작을 커스터마이징하고 싶다면
단순히 인자를 포워딩만 하는 fallback <code class="language-plaintext highlighter-rouge">await_transform()</code> 오버로드를 추가로 제공해야 한다는 말이다.</p>

<h3 id="co_yield의-동작-커스터마이징"><code class="language-plaintext highlighter-rouge">co_yield</code>의 동작 커스터마이징</h3>

<p>마지막으로 promise 타입을 이용해 커스터마이징 할 수 있는 것은 <code class="language-plaintext highlighter-rouge">co_yield</code> 키워드의 동작이다.</p>

<p><code class="language-plaintext highlighter-rouge">co_yield</code> 키워드가 코루틴에서 나타나면 컴파일러는 <code class="language-plaintext highlighter-rouge">co_yield &lt;expr&gt;</code> 표현식을 <code class="language-plaintext highlighter-rouge">co_await promise.yield_value(&lt;expr&gt;)</code> 표현식으로 번역한다.<br />
고로 promise 객체가 쓸 <code class="language-plaintext highlighter-rouge">yield_value()</code> 메서드를 하나 이상 정의함으로써 <code class="language-plaintext highlighter-rouge">co_yield</code> 키워드의 동작을 커스터마이징 할 수 있다.</p>

<p><code class="language-plaintext highlighter-rouge">await_transform</code>과는 달리, <code class="language-plaintext highlighter-rouge">yield_value()</code> 메서드가 정의되어 있지 않으면 <code class="language-plaintext highlighter-rouge">co_yield</code> 키워드의 기본 동작이 존재하지 않는다는 점을 유념하라.<br />
고로 promise 타입에서 <code class="language-plaintext highlighter-rouge">co_await</code> 지원을 제거하려면 명시적으로 <code class="language-plaintext highlighter-rouge">await_transform()</code>을 delete로 선언해야 하는 반면<sub>opt-out</sub>,
<code class="language-plaintext highlighter-rouge">co_yield</code>를 지원하려면 명시적으로 <code class="language-plaintext highlighter-rouge">yield_value()</code>를 정의해야 한다<sub>opt-in</sub>.</p>

<p>promise 타입이 <code class="language-plaintext highlighter-rouge">yield_value()</code> 메서드를 지원하는 전형적인 예는 <code class="language-plaintext highlighter-rouge">generator&lt;T&gt;</code> 타입의 경우이다:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">template</span><span class="o">&lt;</span><span class="k">typename</span> <span class="nc">T</span><span class="p">&gt;</span>
<span class="k">class</span> <span class="nc">generator_promise</span>
<span class="p">{</span>
  <span class="n">T</span><span class="o">*</span> <span class="n">valuePtr</span><span class="p">;</span>
<span class="nl">public:</span>
  <span class="p">...</span>

  <span class="n">std</span><span class="o">::</span><span class="n">suspend_always</span> <span class="n">yield_value</span><span class="p">(</span><span class="n">T</span><span class="o">&amp;</span> <span class="n">value</span><span class="p">)</span> <span class="k">noexcept</span>
  <span class="p">{</span>
    <span class="c1">// yield된 값의 주소를 저장한 후 co_yield 표현식에서 코루틴을 중단시키는</span>
    <span class="c1">// awaitable을 반환한다. 그러면 제어는 generator&lt;T&gt;::begin() 이나</span>
    <span class="c1">// generator&lt;T&gt;::iterator::operator++() 안에서 호출된</span>
    <span class="c1">// coroutine_handle&lt;&gt;::resume() 호출로 되돌아갈 것이다.</span>
    <span class="n">valuePtr</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">addressof</span><span class="p">(</span><span class="n">value</span><span class="p">);</span>
    <span class="k">return</span> <span class="p">{};</span>
  <span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>

<h1 id="symmetric-transfer-이해하기">Symmetric Transfer 이해하기</h1>

<p>(WIP)</p>

<h2 id="task-코루틴-작동방식-배경-설명">task 코루틴 작동방식 배경 설명</h2>

<p>(WIP)</p>

<h2 id="task-구현-개요outline"><code class="language-plaintext highlighter-rouge">task</code> 구현 개요<sub>Outline</sub></h2>

<p>(WIP)</p>

<h2 id="taskpromise_type-구현하기"><code class="language-plaintext highlighter-rouge">task::promise_type</code> 구현하기</h2>

<p>(WIP)</p>

<h2 id="taskoperator-co_await-구현하기"><code class="language-plaintext highlighter-rouge">task::operator co_await()</code> 구현하기</h2>

<p>(WIP)</p>

<h2 id="스택-오버플로-문제">스택 오버플로 문제</h2>

<p>(WIP)</p>

<h2 id="코루틴-ts-해결책">코루틴 TS 해결책</h2>

<p>(WIP)</p>

<h2 id="여전한-문제점">여전한 문제점</h2>

<p>(WIP)</p>

<h2 id="symmetric-transfer-입장">“symmetric transfer” 입장!</h2>

<p>Gor Nishanov가 2018년에 작성한 <a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0913r0.html">P0913R0</a> 제안서<sub>paper</sub> “Add symmetric coroutine control transfer”는
한 코루틴이 중단될 때 추가적인 스택 공간 사용 없이 다른 코루틴이 대칭적으로<sub>symmetrically</sub> 재개되도록 하는 기능<sub>facility</sub>을 제공하도록 하는 이 문제의 해결책을 제안했다.</p>

<p>이 제안서<sub>paper</sub>는 2가지 핵심 변경사항을 제안했다:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">await_suspend()</code>에서 <code class="language-plaintext highlighter-rouge">std::coroutine_handle&lt;T&gt;</code>를 반환하는 것을 허용한다.
그게 반환되면 실행 흐름이 반환된 핸들로 나타내어지는 코루틴으로 대칭적으로 전달<sub>symmetrically transferred</sub>되어야 함을 의미한다.</li>
  <li><code class="language-plaintext highlighter-rouge">std::noop_coroutine()</code> 함수를 추가한다.
이 함수는 <code class="language-plaintext highlighter-rouge">await_suspend()</code>에서 반환될 수 있는 특수한 <code class="language-plaintext highlighter-rouge">std::coroutine_handle</code>을 가져오는데,
이걸 반환하면 다른 코루틴으로 실행 흐름을 전달하는 대신 현재 코루틴을 중단시킨 후 <code class="language-plaintext highlighter-rouge">.resume()</code> 호출을 반환시킨다.</li>
</ul>

<p>그래서, “대칭적으로 전달<sub>symmetric transfer</sub>“한다는 게 무슨 의미일까?</p>

<p>코루틴을 <code class="language-plaintext highlighter-rouge">std::coroutine_handle</code>의 <code class="language-plaintext highlighter-rouge">.resume()</code> 호출로 재개하면 코루틴이 실행되는 동안 <code class="language-plaintext highlighter-rouge">.resume()</code> 호출자의 스택이 활성화된 상태로 남아있게 된다.<br />
이 코루틴이 다음번에 중단되고 그 중단점의 <code class="language-plaintext highlighter-rouge">await_suspend()</code> 호출이 <code class="language-plaintext highlighter-rouge">void</code>를 반환하거나 (무조건 중단) <code class="language-plaintext highlighter-rouge">true</code>를 반환해야 (조건부 중단) 그제야 <code class="language-plaintext highlighter-rouge">.resume()</code> 호출이 반환된다.</p>

<p>이것은 “비대칭적인 전달<sub>asymmetric transfer</sub>“이라고 여겨질 수 있고, 서브루틴 호출과 똑같이 동작한다.<br />
<code class="language-plaintext highlighter-rouge">.resume()</code>의 호출자는 아무 함수나 될 수 있다 (코루틴일 수도 아닐 수도 있다).</p>

<p>코루틴을 <code class="language-plaintext highlighter-rouge">.resume()</code> 호출로 재개할 때마다 그 코루틴을 실행하기 위한 새로운 스택 프레임을 생성하는 것이다.</p>

<p>하지만, “symmetric transfer”에서는 그저 한 코루틴을 중단시키고 다른 코루틴을 재개할 뿐이다.<br />
두 코루틴 사이에는 암시적인 호출자/피호출자 관계가 없다.
코루틴이 중단되면 제어를 아무 코루틴에게나(자기 자신 포함) 전달할 수 있지, 중단/완료되었을 때 제어를 꼭 이전 코루틴에게 전달할 필요는 없다.</p>

<p>symmetric-transfer를 사용할 때 컴파일러가 <code class="language-plaintext highlighter-rouge">co_await</code> 표현식을 어떻게 lower하는지 보자:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
  <span class="k">decltype</span><span class="p">(</span><span class="k">auto</span><span class="p">)</span> <span class="n">value</span> <span class="o">=</span> <span class="o">&lt;</span><span class="n">expr</span><span class="o">&gt;</span><span class="p">;</span>
  <span class="k">decltype</span><span class="p">(</span><span class="k">auto</span><span class="p">)</span> <span class="n">awaitable</span> <span class="o">=</span>
      <span class="n">get_awaitable</span><span class="p">(</span><span class="n">promise</span><span class="p">,</span> <span class="k">static_cast</span><span class="o">&lt;</span><span class="k">decltype</span><span class="p">(</span><span class="n">value</span><span class="p">)</span><span class="o">&amp;&amp;&gt;</span><span class="p">(</span><span class="n">value</span><span class="p">));</span>
  <span class="k">decltype</span><span class="p">(</span><span class="k">auto</span><span class="p">)</span> <span class="n">awaiter</span> <span class="o">=</span>
      <span class="n">get_awaiter</span><span class="p">(</span><span class="k">static_cast</span><span class="o">&lt;</span><span class="k">decltype</span><span class="p">(</span><span class="n">awaitable</span><span class="p">)</span><span class="o">&amp;&amp;&gt;</span><span class="p">(</span><span class="n">awaitable</span><span class="p">));</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">awaiter</span><span class="p">.</span><span class="n">await_ready</span><span class="p">())</span>
  <span class="p">{</span>
    <span class="k">using</span> <span class="n">handle_t</span> <span class="o">=</span> <span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;</span><span class="n">P</span><span class="o">&gt;</span><span class="p">;</span>

    <span class="c1">//&lt;suspend-coroutine&gt;</span>

    <span class="k">auto</span> <span class="n">h</span> <span class="o">=</span> <span class="n">awaiter</span><span class="p">.</span><span class="n">await_suspend</span><span class="p">(</span><span class="n">handle_t</span><span class="o">::</span><span class="n">from_promise</span><span class="p">(</span><span class="n">p</span><span class="p">));</span>
    <span class="n">h</span><span class="p">.</span><span class="n">resume</span><span class="p">();</span>
    <span class="c1">//&lt;return-to-caller-or-resumer&gt;</span>

    <span class="c1">//&lt;resume-point&gt;</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="n">awaiter</span><span class="p">.</span><span class="n">await_resume</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>다른 <code class="language-plaintext highlighter-rouge">co_await</code> 형태와는 다른 중요한 부분에 주목해보겠다:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">auto</span> <span class="n">h</span> <span class="o">=</span> <span class="n">awaiter</span><span class="p">.</span><span class="n">await_suspend</span><span class="p">(</span><span class="n">handle_t</span><span class="o">::</span><span class="n">from_promise</span><span class="p">(</span><span class="n">p</span><span class="p">));</span>
<span class="n">h</span><span class="p">.</span><span class="n">resume</span><span class="p">();</span>
<span class="c1">//&lt;return-to-caller-or-resumer&gt;</span>
</code></pre></div></div>

<p>상태 기계가 lowered되면 (나중에 다룰 예정), <code class="language-plaintext highlighter-rouge">&lt;return-to-caller-or-resumer&gt;</code> 부분이 <code class="language-plaintext highlighter-rouge">return;</code> 문이 되어
마지막으로 코루틴을 재개한 <code class="language-plaintext highlighter-rouge">.resume()</code> 호출이 호출자에게 반환된다.</p>

<p>이 말은 현재 함수의 몸체가 <code class="language-plaintext highlighter-rouge">std::coroutine_handle::resume()</code>인데 그 안에서
동일 시그니처의 또 다른 <code class="language-plaintext highlighter-rouge">std::coroutine_handle::resume()</code> 호출 직후에 <code class="language-plaintext highlighter-rouge">return;</code>을 하는 상황이라는 것이다.</p>

<p>일부 컴파일러들은, 최적화가 켜져 있을 때, 몇몇 조건이 만족되면 tail-position(반환 직전)에 있는 다른 함수 호출을 꼬리 호출<sub>tail-calls</sub>로 바꾸는 최적화를 수행할 수 있다.</p>

<p>우연히도 우리가 하고자 하는 스택 오버플로 문제의 해결을 이 꼬리 호출 최적화<sub>tail-call optimisation</sub>가 해줄 수 있다.<br />
하지만 최적화가 되길 간절히 바라는 대신, 우리는 최적화가 꺼져 있더라고 이 꼬리 호출 변환이 항상 일어나는 게 보장되길 원한다.</p>

<p>하지만 우선 꼬리 호출<sub>tail-calls</sub>이 뭔지부터 파보자.</p>

<h2 id="꼬리-호출tail-calls">꼬리 호출<sub>Tail-calls</sub></h2>

<p>(WIP)</p>

<h2 id="task-재작성하기revisited"><code class="language-plaintext highlighter-rouge">task</code> 재작성하기<sub>revisited</sub></h2>

<p>새로운 “symmetric transfer” 기능<sub>capability</sub>을 머릿속에 넣었다면<sub>under our belt</sub> 우리의 이전 <code class="language-plaintext highlighter-rouge">task</code> 타입 구현을 고칠 차례다.</p>

<p>그러려면 두 <code class="language-plaintext highlighter-rouge">await_suspend()</code> 메서드의 구현을 고쳐야 한다:</p>
<ol>
  <li>task를 await할 때 해당 task의 코루틴을 symmetric-transfer로 재개하도록</li>
  <li>task의 코루틴이 완료됐을 때 대기하는 코루틴을 symmetric-transfer로 재개하도록</li>
</ol>

<p>await되는 방향을 나타내려면<sub>address</sub> <code class="language-plaintext highlighter-rouge">task::awaiter</code>의 메서드를 이것에서:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">task</span><span class="o">::</span><span class="n">awaiter</span><span class="o">::</span><span class="n">await_suspend</span><span class="p">(</span>
    <span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;&gt;</span> <span class="n">continuation</span><span class="p">)</span> <span class="k">noexcept</span> <span class="p">{</span>
  <span class="c1">// continuation을 task의 promise에 저장해놓음으로써 task가 완료됐을 때</span>
  <span class="c1">// final_suspend()가 이 코루틴을 재개해야 한다는 것을 알게 한다.</span>
  <span class="n">coro_</span><span class="p">.</span><span class="n">promise</span><span class="p">().</span><span class="n">continuation</span> <span class="o">=</span> <span class="n">continuation</span><span class="p">;</span>

  <span class="c1">// 그 후 현재 initial-suspend-point(중괄호 오픈)에 중단되어 있는</span>
  <span class="c1">// task의 코루틴을 재개한다.</span>
  <span class="n">coro_</span><span class="p">.</span><span class="n">resume</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>
<p>이 모습으로 수정해야 한다:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;&gt;</span> <span class="n">task</span><span class="o">::</span><span class="n">awaiter</span><span class="o">::</span><span class="n">await_suspend</span><span class="p">(</span>
    <span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;&gt;</span> <span class="n">continuation</span><span class="p">)</span> <span class="k">noexcept</span> <span class="p">{</span>
  <span class="c1">// continuation을 task의 promise에 저장해놓음으로써 task가 완료됐을 때</span>
  <span class="c1">// final_suspend()가 이 코루틴을 재개해야 한다는 것을 알게 한다.</span>
  <span class="n">coro_</span><span class="p">.</span><span class="n">promise</span><span class="p">().</span><span class="n">continuation</span> <span class="o">=</span> <span class="n">continuation</span><span class="p">;</span>

  <span class="c1">// 그 후 현재 initial-suspend-point(중괄호 오픈)에 중단되어 있는</span>
  <span class="c1">// task의 코루틴을, 핸들을 반환함으로써 꼬리-재개한다.</span>
  <span class="k">return</span> <span class="n">coro_</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>그리고 return-path를 나타내려면<sub>address</sub> <code class="language-plaintext highlighter-rouge">task::promise_type::final_awaiter</code> 메서드를 이것에서:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">task</span><span class="o">::</span><span class="n">promise_type</span><span class="o">::</span><span class="n">final_awaiter</span><span class="o">::</span><span class="n">await_suspend</span><span class="p">(</span>
    <span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;</span><span class="n">promise_type</span><span class="o">&gt;</span> <span class="n">h</span><span class="p">)</span> <span class="k">noexcept</span> <span class="p">{</span>
  <span class="c1">// 이제 코루틴이 final-suspend 위치에서 중단되었다.</span>
  <span class="c1">// promise에서 continuation을 찾아 재개한다.</span>
  <span class="n">h</span><span class="p">.</span><span class="n">promise</span><span class="p">().</span><span class="n">continuation</span><span class="p">.</span><span class="n">resume</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>
<p>이 모습으로 수정해야 한다:</p>
<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;&gt;</span> <span class="n">task</span><span class="o">::</span><span class="n">promise_type</span><span class="o">::</span><span class="n">final_awaiter</span><span class="o">::</span><span class="n">await_suspend</span><span class="p">(</span>
    <span class="n">std</span><span class="o">::</span><span class="n">coroutine_handle</span><span class="o">&lt;</span><span class="n">promise_type</span><span class="o">&gt;</span> <span class="n">h</span><span class="p">)</span> <span class="k">noexcept</span> <span class="p">{</span>
  <span class="c1">// 이제 코루틴이 final-suspend 위치에서 중단되었다.</span>
  <span class="c1">// promise에서 continuation을 찾아 symmetrical하게 재개한다.</span>
  <span class="k">return</span> <span class="n">h</span><span class="p">.</span><span class="n">promise</span><span class="p">().</span><span class="n">continuation</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>이제 우리 <code class="language-plaintext highlighter-rouge">task</code> 구현은 <code class="language-plaintext highlighter-rouge">void</code>를 반환하는 <code class="language-plaintext highlighter-rouge">await_suspend</code> 방식<sub>flavour</sub>에서 있었던 스택 오버플로 문제에서 자유로우며,
<code class="language-plaintext highlighter-rouge">bool</code>을 반환하는 <code class="language-plaintext highlighter-rouge">await_suspend</code> 방식<sub>flavour</sub>에서 있었던 비결정론적인<sub>non-deterministic</sub> 재개 컨텍스트 문제에서 자유롭다.</p>

<h3 id="스택-시각화하기">스택 시각화하기</h3>

<p>(WIP)</p>

<p>symmetric-transfer 버전의 <code class="language-plaintext highlighter-rouge">task</code> 타입 예제를 보고 싶다면 이 Compiler Explorer 링크를 참조하라: <a href="https://godbolt.org/z/9baieF">https://godbolt.org/z/9baieF</a></p>

<h2 id="await_suspend의-보편적-형태the-universal-form로서의-symmetric-transfer"><code class="language-plaintext highlighter-rouge">await_suspend</code>의 보편적 형태<sub>the Universal Form</sub>로서의 Symmetric Transfer</h2>

<p>(WIP)</p>

<h3 id="재귀를-종료하기terminating">재귀를 종료하기<sub>Terminating</sub></h3>

<p>(WIP)</p>

<h3 id="다른-모습flavours의-await_suspend를-표현하기">다른 모습<sub>flavours</sub>의 <code class="language-plaintext highlighter-rouge">await_suspend()</code>를 표현하기</h3>

<p>(WIP)</p>

<h3 id="그럼-왜-3개의-모습flavours을-둬야-하나">그럼 왜 3개의 모습<sub>flavours</sub>을 둬야 하나?</h3>

<p>(WIP)</p>

<h1 id="참고자료">참고자료</h1>

<ul>
  <li><a href="https://lewissbaker.github.io">Lewis Baker - Asymmetric Transfer</a>
    <ul>
      <li><a href="https://github.com/lewissbaker/cppcoro">cppcoro</a> 개발자의 코루틴 설명 블로그.</li>
    </ul>
  </li>
  <li><a href="https://en.cppreference.com/w/cpp/language/coroutines.html">cppreference.com - Coroutines</a></li>
</ul>

<p><em>마지막 수정 : 2025-10-13 17:33:00 +0900</em></p>]]></content><author><name>copyrat90</name></author><category term="C++" /><summary type="html"><![CDATA[C++20 표준에 도입된 코루틴은 대체 뭐고, 어떻게 쓰는가?]]></summary></entry><entry><title type="html">butano-ldtk 최적화</title><link href="https://copyrat90.github.io/2025/09/01/butano-ldtk-bg-optimization.html" rel="alternate" type="text/html" title="butano-ldtk 최적화" /><published>2025-09-01T00:00:00+00:00</published><updated>2025-08-31T16:44:00+00:00</updated><id>https://copyrat90.github.io/2025/09/01/butano-ldtk-bg-optimization</id><content type="html" xml:base="https://copyrat90.github.io/2025/09/01/butano-ldtk-bg-optimization.html"><![CDATA[<p>GBA 엔진용 LDtk 레벨 로더 구현 중 최적화했던 부분.</p>

<p>최근 몇주간 <a href="https://github.com/GValiente/butano">Butano engine</a>용 <a href="https://github.com/copyrat90/butano-ldtk">LDtk 레벨 로더</a>를 짜던 중이었다.</p>

<p>대충 원리는 Python으로 <code class="language-plaintext highlighter-rouge">my_project.ldtk</code> 파일을 적절히 파싱한 후, C++ <code class="language-plaintext highlighter-rouge">constexpr</code> 객체들을 담은 헤더 파일을 codegen하는 것이다.<br />
그리고 그걸 이용해서 레벨 배경을 조작하는 <code class="language-plaintext highlighter-rouge">ldtk::level_bgs_ptr</code> 클래스도 추가로 제공한다.</p>

<p>여튼 그걸 설명하려던 건 아니고, 배경 렌더링 부분을 최적화한 일지를 남기려고 한다.</p>

<h1 id="최초-구현-느려터짐">최초 구현 (느려터짐)</h1>

<p><a href="https://github.com/copyrat90/butano-ldtk/commit/7d688b75effc1c91298577e230a462edb0d5ee39">최초 commit</a></p>

<p>가장 naive한 첫번째 렌더링 구현.</p>
<ul>
  <li>카메라 이동시마다 화면에 보이는 모든 타일을 전부 리로드</li>
  <li>배경 레이어 당 virtual function call 31(열)×21(행) = 651회
    <ul>
      <li>GBA 해상도가 240x160이고, tile은 8x8이므로, 나누면 30x20일 것 같지만,<br />
대부분의 경우 옆 1줄에 추가로 걸치기 때문에 31x21이 된다.</li>
    </ul>
  </li>
  <li>div, mod 마구마구 사용</li>
</ul>

<p><img src="/assets/img/posts/2025-09-01-butano-ldtk-bg-optimization/naivest.gif" alt="" /></p>

<p>느릴 거라 예상하긴 했지만, 상상 이상의 CPU 사용률이 나온다.<br />
GBA 에뮬레이터 <a href="https://github.com/SourMesen/Mesen2">Mesen2</a>로 profiling을 해보자…</p>

<p><img src="/assets/img/posts/2025-09-01-butano-ldtk-bg-optimization/naivest_profiler.png" alt="" /></p>

<p><code class="language-plaintext highlighter-rouge">bg_t::reset_all_cells()</code> 함수 안에서 94.5% (inclusive) CPU를 사용중이다.<br />
그 바로 밑에 <code class="language-plaintext highlighter-rouge">thumb_8000F98</code> 함수가 19.5% (exclusive)를 먹는데,<br />
이 녀석의 Call Count를 위 함수의 Call Count로 나누면 650.4589번이다.<br />
이건 8x8 tile cell마다 호출되는 virtual function일 가능성이 높다.</p>

<p>virtual function을 사용하는 이유는, meta-tile 가짓수에 따라 타일 정보를 저장하는 크기가 달라지는데 (<code class="language-plaintext highlighter-rouge">u8</code>/<code class="language-plaintext highlighter-rouge">u16</code>),<br />
이걸 타입을 모르는 채로 generic하게 받아오기 위함이었다.<br />
근데 이걸 각 cell마다 매번 virtual function call로 받아오고 있으니 느려터진다.</p>

<p>정확히는 배경 레이어가 3개이므로, 프레임당 3 × 651 = 1953번 호출되고 있다.
1번만 호출 -&gt; 구체 타입 파악 -&gt; <code class="language-plaintext highlighter-rouge">static_cast</code>를 해서 구체 타입의 함수를 호출하는 최적화가 떠오른다.</p>

<h1 id="1차-최적화-가상함수-호출-횟수-줄이기">1차 최적화: 가상함수 호출 횟수 줄이기</h1>

<p><a href="https://github.com/copyrat90/butano-ldtk/commit/0688150a705b0beb712e8459cac658b4fbb546c4">가상 함수 651회 -&gt; 1회 최적화 commit</a></p>

<p>성능을 위해 <code class="language-plaintext highlighter-rouge">dynamic_cast</code>는 비활성화된 상태이므로, 그냥 타입을 알려주는 <code class="language-plaintext highlighter-rouge">tile_grid_t::bloated()</code> 가상함수를 하나 만들고,<br />
그걸 호출해 구체 타입을 파악 -&gt; <code class="language-plaintext highlighter-rouge">static_cast</code>를 해서 구체 타입의 함수를 호출하도록 최적화했다.<br />
(어찌 보면 직접 빚은 <code class="language-plaintext highlighter-rouge">dynamic_cast</code>라고 볼 수도 있겠다.)</p>

<p>그리고 가상함수는 초기화시 1회만 호출해 구체 타입을 파악하므로, 프레임당 가상함수 호출은 아예 없어졌다.<br />
대신에 매번 <code class="language-plaintext highlighter-rouge">grid_bloated</code> 플래그를 판단하는 것으로 대체되었다.</p>

<p><img src="/assets/img/posts/2025-09-01-butano-ldtk-bg-optimization/no_virtual.gif" alt="" /></p>

<p>57%의 CPU를 아꼈다.<br />
배경 레이어가 3개나 된다는 것치곤 성능 변화가 아주 크진 않다.</p>

<p><img src="/assets/img/posts/2025-09-01-butano-ldtk-bg-optimization/no_virtual_profiler.png" alt="" /></p>

<p>다음으로 많아보이는 건 divmod 등 정수 나눗셈 관련 코드다.<br />
대부분의 나눗셈을 그냥 직전 루프의 누적합으로 대체할 수 있을 것으로 보인다.</p>

<h1 id="2차-최적화-divmod-제거">2차 최적화: divmod 제거</h1>

<p><a href="https://github.com/copyrat90/butano-ldtk/commit/1b23f55333b395b691b96b319184d690ab519a83">divmod 호출 제거 commit</a></p>

<p>divmod를 초기에 1회만 나눗셈으로 구하고, 그 이후엔 누적합 -&gt; 자리올림을 직접 하는 코드로 대체했다.<br />
누적 카운터를 계속 +1 한 후 조건 판단하는 것이, 정수 나눗셈을 매번 반복하는 것보다는 훨씬 싸게 먹힌다.</p>

<p><img src="/assets/img/posts/2025-09-01-butano-ldtk-bg-optimization/no_divmod.gif" alt="" /></p>

<p>무려 205%의 CPU를 아꼈다.</p>

<p><img src="/assets/img/posts/2025-09-01-butano-ldtk-bg-optimization/no_divmod_profiler.png" alt="" /></p>

<p>이젠 그냥 <code class="language-plaintext highlighter-rouge">reset_all_cells()</code> 함수 자체가 하는 일이 많은 것 같다.<br />
애초에 651개의 tile cell 전체를 순회하며 업데이트 하는 것 자체가 느리다.</p>

<p>대부분의 경우, 화면 이동 시에 기존 tile map 전체를 다시 로드할 필요는 없다.<br />
위 이동의 경우도, 프레임당 1-2줄의 행/열이 추가되는 것을 제외하고는, 기존 타일은 재렌더링 없이 그대로 쓸 수 있다.</p>

<p>즉, 이동 시에는 업데이트된 1-2줄만 다시 렌더링하도록 최적화를 하면 된다.</p>

<h1 id="3차-최적화-변경된-부분만-다시-그리기">3차 최적화: 변경된 부분만 다시 그리기</h1>

<p><a href="https://github.com/copyrat90/butano-ldtk/commit/21ab9bcf241313b1709bcfd538d6945a59bd93be">변경된 타일맵만 다시 그리는 commit</a></p>

<p>이동시 새로 보이기 시작한 범위만 다시 그리도록 재구현했다.</p>

<p><img src="/assets/img/posts/2025-09-01-butano-ldtk-bg-optimization/row_col.gif" alt="" /></p>

<p>이번엔 300%는 아꼈다.<br />
이제 이동 중에 대략 30%의 CPU만 먹는다.<br />
이 정도면 당장은 충분할 것 같다.</p>

<p>처음으로 배경을 생성할 때는 300%가 넘긴 하는데,<br />
대부분의 경우 레벨 변경 시 약간의 딜레이는 큰 문제는 아닐 것이다.</p>

<p><em>마지막 수정 : 2025-09-01 01:44:00 +0900</em></p>]]></content><author><name>copyrat90</name></author><category term="Devlog" /><summary type="html"><![CDATA[GBA 엔진용 LDtk 레벨 로더 구현 중 최적화했던 부분.]]></summary></entry><entry><title type="html">Multi Plaza 개발일지 (02) - Snapshot Interpolation 구현</title><link href="https://copyrat90.github.io/2025/06/27/multi-plaza-devlog-02.html" rel="alternate" type="text/html" title="Multi Plaza 개발일지 (02) - Snapshot Interpolation 구현" /><published>2025-06-27T00:00:00+00:00</published><updated>2025-06-30T06:39:00+00:00</updated><id>https://copyrat90.github.io/2025/06/27/multi-plaza-devlog-02</id><content type="html" xml:base="https://copyrat90.github.io/2025/06/27/multi-plaza-devlog-02.html"><![CDATA[<p>플레이어 위치 동기화를 하기 위해, Snapshot Interpolation을 내 방식으로 구현했다.</p>

<p>이번에도 YouTube 영상부터.</p>

<h1 id="테스트-영상">테스트 영상</h1>

<p><a href="https://www.youtube.com/watch?v=yw4ub8FqlTc"><img src="https://img.youtube.com/vi/yw4ub8FqlTc/hqdefault.jpg" alt="" /></a></p>

<h1 id="개념">개념</h1>

<p>Snapshot Interpolation 개념에 대해서는 인터넷에 좋은 자료가 많다.</p>
<ul>
  <li><a href="/2025/04/05/fast-paced-multiplayer-3#entity-interpolation">Fast-Paced Multiplayer (Part III) - Entity Interpolation (내 번역)</a></li>
  <li><a href="https://gafferongames.com/post/snapshot_interpolation/">Gaffer on Games - Snapshot Interpolation</a></li>
  <li><a href="https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking#Entity_interpolation">Valve: Source Multiplayer Networking - Entity interpolation</a></li>
</ul>

<p>위 글들 중 Valve가 쓴 글에 있는 이미지를 빌려와서 초간단 요약하자면…
<img src="https://developer.valvesoftware.com/w/images/thumb/f/ff/Source_Multiplayer_Networking_-_Interpolation.png/750px-Source_Multiplayer_Networking_-_Interpolation.png" alt="" /></p>

<p>네트워크로부터 다른 플레이어의 위치 정보<sub>Snapshot</sub>가 특정 주기<sub>Snapshot Interval</sub>로 수신된다.<br />
(e.g. 위 이미지 상으로는 매 0.05초마다 수신)</p>

<p>이를 이용한 가장 간단한 위치 동기화 방법은, 수신된 위치로 즉시 워프하는 것을 반복하는 것이다.<br />
하지만 그 방식은 문제점이 많다.</p>

<ul>
  <li>0.05초마다 받은 위치를 그대로 렌더링하면 20 fps가 되는데, 끊겨 보일것이다.</li>
  <li>네트워크 환경상 들쭉날쭉<sub>jitter</sub>한 수신은 필연적이라,<br />
어떤 때는 순식간에 여러번 워프하고, 어떤 때는 한참 제자리에 있고 할 것이다.</li>
  <li>UDP 송신 시 패킷 순서가 뒤섞이거나, 아예 유실될 수도 있는데,<br />
그러면 갑자기 뒤로 이동하거나, 한참 제자리에 있다가 저 멀리로 워프할 것이다.</li>
</ul>

<p>그러므로, 최소한 위치 정보를 2개는<sub>#340, #342</sub> 받은 시점부터 시작해, 두 위치 정보 사이를 시간에 따라<sub>Current Rendering Time</sub> 보간<sub>Interpolation</sub>해서 렌더링하는 게 기본이다.</p>

<p>여기에 추가로, 들쭉날쭉한/뒤섞인/유실된 수신에 대응하기 위해서, 즉시 렌더링하지 않고 조금 딜레이를 둬서 렌더링을 시작한다.<br />
(e.g. 위 이미지상으로는 Interpolation Time이 0.1초이므로, 2개의 Snapshot을 받아도 평균 0.05초는 더 기다렸다가 렌더링을 시작하게 된다.)</p>

<p>딜레이를 더 두는 점은, 유튜브의 버퍼링을 생각하면 이해가 쉬울 것이다.<br />
한번 버퍼링이 걸리면, 추가 영상 데이터를 꽤 많이 버퍼링한 다음에야 재생이 재개되는데, 또 끊기는 걸 최소화하기 위해서다.</p>

<h1 id="내-프로토콜의-차이점">내 프로토콜의 차이점</h1>

<p>보통 구현을 보면, Unreliable한 패킷을 가만히 정지해 있을 때도 계속 보내주는 식으로 구현하는 경우가 꽤 있다.<br />
예를 들어 <a href="https://mirror-networking.gitbook.io/docs/manual/components/network-transform/snapshot-interpolation#using-the-algorithm">Mirror의 Snapshot Interpolation: Using the algorithm</a>을 보면, 다음과 같은 경고문이 써있다:</p>

<blockquote>
  <p>Note how <code class="language-plaintext highlighter-rouge">NetworkTransform</code> sends snapshots <strong>every</strong> <code class="language-plaintext highlighter-rouge">sendInterval</code> over the <strong>unreliable</strong> channel. Do not send <strong>only if changed</strong>, this would require knowledge about the other end’s last received snapshot (either over <strong>reliable</strong>, or with a <strong>notify</strong> algorithm).</p>
</blockquote>

<p>하지만 가만히 있는데 위치 정보를 주기적으로 보내는 건 너무 낭비가 심한데…</p>

<p>사실, 위 경고문을 토대로 잘 생각해보면, 마지막으로 정지한 위치를 reliable하게 공유하기만 하면 된다는 것을 알 수 있다. 그러면 같은 위치에 멈출 수 있을 테니.<br />
그래서, 내가 정의한 프로토콜에서는, <strong>이동</strong> 중에 보내는 위치는 <strong>Unreliable</strong>하게, <strong>정지</strong>할 때 보내는 위치는 <strong>Reliable</strong>하게 송신한다.</p>

<p>한참 정지해 있다가 이동을 시작하는 경우는, 다시 유튜브 버퍼링으로 비유하면 데이터가 한참 안 오는 상황일 뿐이다.
그냥 2번째 Snapshot이 올 때까지 기다렸다가, 오고 난 후부터 일정 딜레이를 더 기다렸다가 이동을 재개하면 된다.</p>

<h1 id="구현-세부사항">구현 세부사항</h1>

<h2 id="payload">Payload</h2>

<p>일단 네트워크에서 수신한 시간은 믿을 수가 없으므로, 위치를 보내는 측에서 Snapshot에 시퀀스 번호<sub>sequence number</sub>를 넣어서 보내야 한다.<br />
1초에 10번 보낸다고 치면, 시퀀스 번호가 +1 증가한 Snapshot은 직전 위치 Snapshot으로부터 100 ms 이후의 위치 정보라는 것을 알 수 있다.</p>

<p>시퀀스 번호는 간단히 2 bytes 정수로 하면 될 것 같다.
그런데 overflow가 일어나면, 어느 게 더 최신 Snapshot일지 어떻게 판단할까?</p>

<p><a href="https://gafferongames.com/post/reliability_ordering_and_congestion_avoidance_over_udp/#handling-sequence-number-wrap-around">Gaffer on Games - Handling Sequence Number Wrap-Around</a>를 보자:</p>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">inline</span> <span class="n">bool</span> <span class="nf">sequence_greater_than</span><span class="p">(</span> <span class="kt">uint16_t</span> <span class="n">s1</span><span class="p">,</span> <span class="kt">uint16_t</span> <span class="n">s2</span> <span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="p">(</span> <span class="p">(</span> <span class="n">s1</span> <span class="o">&gt;</span> <span class="n">s2</span> <span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span> <span class="n">s1</span> <span class="o">-</span> <span class="n">s2</span> <span class="o">&lt;=</span> <span class="mi">32768</span> <span class="p">)</span> <span class="p">)</span> <span class="o">||</span>
           <span class="p">(</span> <span class="p">(</span> <span class="n">s1</span> <span class="o">&lt;</span> <span class="n">s2</span> <span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span> <span class="n">s2</span> <span class="o">-</span> <span class="n">s1</span>  <span class="o">&gt;</span> <span class="mi">32768</span> <span class="p">)</span> <span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>값이 절반보다 멀리 떨어져 있다면, 한바퀴 돈 것<sub>wrap-around</sub>으로 보고 숫자가 낮은 쪽을 미래 값으로 판정하겠다는 게 핵심이다.<br />
일반적인 <code class="language-plaintext highlighter-rouge">ushort</code>와는 정렬 방식이 달라지다보니, 실수를 막기 위해 별도의 <code class="language-plaintext highlighter-rouge">struct SequenceNumber16 : IComparable&lt;SequenceNumber16&gt;, IEquatable&lt;SequenceNumber16&gt;</code>을 만들어 사용했다.</p>

<p>위치는 그냥 X, Y좌표를 <code class="language-plaintext highlighter-rouge">float</code> 2개로 넣어서 보내자.<br />
(나중에 월드 가장자리 좌표를 확정짓고 나면, 고정 소수점으로 좀 더 압축할 수도 있겠지만, 당장은 모르니.)</p>

<p>그리고 당연히 누가 보냈는지를 알아야하므로, 1 byte의 플레이어 ID가 들어간다.<br />
(현재 프로토콜 상 플레이어는 255명까지만 지원한다. 플레이어 ID 크기를 줄이기 위함도 있고, <code class="language-plaintext highlighter-rouge">Dictionary</code> 대신 고정 크기 배열을 쓰기 위함도 있다.)</p>

<p>따라서 Payload는 다음과 같이 요약된다.</p>

<ul>
  <li>User index (8 bits)</li>
  <li>Client-side sequence number (16 bits)</li>
  <li>Position
    <ul>
      <li>X (float, 32 bits)</li>
      <li>Y (float, 32 bits)</li>
    </ul>
  </li>
</ul>

<p>여기다가 header와 footer를 넣고, <a href="/2025/06/13/multi-plaza-devlog-01.html#2-nalchi--nalchisharp-라이브러리-구현"><code class="language-plaintext highlighter-rouge">nalchi::bit_stream_reader</code> 구현 디테일로 인한 4 bytes ceil을 거치고 나면</a>, 메시지 크기는 16 bytes 가 된다.</p>

<h2 id="snapshot-버퍼">Snapshot 버퍼</h2>

<p>저장하고 있는 Snapshot은 고작해야 서너개에 불과하지만, Unreliable 송신으로 순서가 뒤섞인 패킷을 재정렬할 필요가 있으므로, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2?view=net-9.0"><code class="language-plaintext highlighter-rouge">SortedList&lt;SequenceNumber16,Vector2&gt;</code></a>에 쌓아놓는 게 적절해보인다.</p>

<h2 id="시작-딜레이">시작 딜레이</h2>

<p>Interpolation delay는 <a href="https://gafferongames.com/post/snapshot_interpolation/#handling-real-world-conditions">Gaffer on Games - Snapshot Interpolation: Handling Real World Conditions</a>에 나온 대로, 일단 350 ms를 사용한다.<br />
2번째 메시지가 온 시점까지 이미 100 ms를 기다린 셈이므로, Start delay는 250 ms가 될 것이다.</p>

<p>딜레이가 좀 길어보이긴 하지만, 내 게임 기획상 월드는 로비에 해당하고, 충돌 판정이나 전투 같은 건 없으니 이대로 진행해도 무방할 것 같다.</p>

<h1 id="설계-및-구현">설계 및 구현</h1>

<h2 id="설계">설계</h2>

<p>지원해야 하는 연산은 아래와 같다.</p>

<ul>
  <li>위치 Snapshot을 수신받을 시, <code class="language-plaintext highlighter-rouge">&lt;SequenceNumber16, Vector2&gt;</code>를 버퍼에 추가한다.
    <ul>
      <li>Snapshot을 받은 시점에 2개가 됐을 경우, 일정 딜레이 이후에 재생을 시작한다.
따라서 <code class="language-plaintext highlighter-rouge">현재 시각 + delay</code>에 1번째 Snapshot의 렌더링을 시작하겠다고 표시한다.</li>
    </ul>
  </li>
  <li>현재 시각 기준으로 보간<sub>Interpolation</sub>된 위치를 받아온다.
    <ul>
      <li>Snapshot이 1개뿐이라면, 해당 위치. (0개일 수는 없음)</li>
      <li>아직 1번째 Snapshot의 시작 시각조차 되지 않았다면, 1번째 위치.</li>
      <li>나머지 경우는, 1번째와 2번째 위치를 현 시각에 맞는 위치로 보간해서 반환.
        <ul>
          <li>만일 2번째 위치 초과한 시각까지 됐다면, 1번째 위치를 삭제하고 렌더링 시작 시각 표시를 <code class="language-plaintext highlighter-rouge">(시퀀스 번호 차이 * 100 ms)</code>만큼 증가시킨다.
이후, 남아있는 Snapshot들을 가지고 처음부터 조건 판단을 되풀이한다.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>유저가 나간 자리에 새로 들어오면, 버퍼를 초기화하고 <code class="language-plaintext highlighter-rouge">&lt;초기 시퀀스 번호, 초기 좌표&gt;</code>를 버퍼에 추가한다.</li>
</ul>

<h2 id="구현">구현</h2>

<p>복잡할 줄 알았는데, 구현해놓고 보니 생각보다 짧다.<br />
고로 주석 포함해 전문을 싣는다.</p>

<p>참고로 코드가 Godot Engine과 프로젝트 내 다른 코드에 의존적이라서, 복붙해 쓰시려거든 손 좀 봐야 할 것이다.</p>

<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">namespace</span> <span class="nn">MultiPlaza.Utils</span><span class="p">;</span>

<span class="k">using</span> <span class="nn">System</span><span class="p">;</span>
<span class="k">using</span> <span class="nn">System.Collections.Generic</span><span class="p">;</span>
<span class="k">using</span> <span class="nn">Godot</span><span class="p">;</span>
<span class="k">using</span> <span class="nn">MultiPlaza.Services</span><span class="p">;</span>
<span class="k">using</span> <span class="nn">MultiPlaza.Services.Server.Options</span><span class="p">;</span>

<span class="c1">/// &lt;summary&gt;</span>
<span class="c1">/// &lt;para&gt;Interpolates the position snapshots.&lt;/para&gt;</span>
<span class="c1">/// &lt;para&gt;See &lt;a href="https://gafferongames.com/post/snapshot_interpolation/"&gt;Gaffer on Games: Snapshot Interpolation&lt;/a&gt; for more info.&lt;/para&gt;</span>
<span class="c1">/// &lt;/summary&gt;</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">SnapshotInterpolator</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="k">const</span> <span class="kt">ulong</span> <span class="n">SnapshotInterval</span> <span class="p">=</span> <span class="m">1</span><span class="n">_000_000</span> <span class="p">/</span> <span class="n">WorldServerLoopOptions</span><span class="p">.</span><span class="n">TicksPerSecond</span><span class="p">;</span>
    <span class="k">private</span> <span class="k">const</span> <span class="kt">ulong</span> <span class="n">InterpolationStartDelay</span> <span class="p">=</span> <span class="m">250</span><span class="n">_000</span><span class="p">;</span>

    <span class="k">private</span> <span class="k">const</span> <span class="kt">int</span> <span class="n">DefaultBufferCapacity</span> <span class="p">=</span> <span class="m">8</span><span class="p">;</span>

    <span class="k">private</span> <span class="k">readonly</span> <span class="n">SortedList</span><span class="p">&lt;</span><span class="n">SequenceNumber16</span><span class="p">,</span> <span class="n">Vector2</span><span class="p">&gt;</span> <span class="n">snapshots</span><span class="p">;</span>

    <span class="k">private</span> <span class="kt">ulong</span> <span class="n">firstSnapshotTime</span><span class="p">;</span>

    <span class="c1">/// &lt;summary&gt;</span>
    <span class="c1">/// Initializes a new instance of the &lt;see cref="SnapshotInterpolator"/&gt; class.</span>
    <span class="c1">/// &lt;/summary&gt;</span>
    <span class="c1">/// &lt;param name="capacity"&gt;Initial buffer capacity.&lt;/param&gt;</span>
    <span class="k">public</span> <span class="nf">SnapshotInterpolator</span><span class="p">(</span><span class="kt">int</span> <span class="n">capacity</span> <span class="p">=</span> <span class="n">DefaultBufferCapacity</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span> <span class="p">=</span> <span class="k">new</span><span class="p">(</span><span class="n">capacity</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c1">/// &lt;summary&gt;</span>
    <span class="c1">/// Gets the number of snapshots in the interpolator.</span>
    <span class="c1">/// &lt;/summary&gt;</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">Count</span> <span class="p">=&gt;</span> <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span>

    <span class="c1">/// &lt;summary&gt;</span>
    <span class="c1">/// &lt;para&gt;Resets the interpolator with the given position.&lt;/para&gt;</span>
    <span class="c1">/// &lt;para&gt;This &lt;b&gt;must&lt;/b&gt; be called first before doing anything.&lt;/para&gt;</span>
    <span class="c1">/// &lt;/summary&gt;</span>
    <span class="c1">/// &lt;param name="sequence"&gt;Initial sequence number.&lt;/param&gt;</span>
    <span class="c1">/// &lt;param name="initialPosition"&gt;Initial position.&lt;/param&gt;</span>
    <span class="k">public</span> <span class="k">void</span> <span class="nf">Reset</span><span class="p">(</span><span class="n">SequenceNumber16</span> <span class="n">sequence</span><span class="p">,</span> <span class="n">Vector2</span> <span class="n">initialPosition</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">Clear</span><span class="p">();</span>
        <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">sequence</span><span class="p">,</span> <span class="n">initialPosition</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c1">/// &lt;summary&gt;</span>
    <span class="c1">/// Adds a snapshot to the interpolator, using &lt;see cref="Time.GetTicksUsec"/&gt; as a current time.</span>
    <span class="c1">/// &lt;/summary&gt;</span>
    <span class="c1">/// &lt;param name="sequence"&gt;Snapshot sequence number.&lt;/param&gt;</span>
    <span class="c1">/// &lt;param name="position"&gt;Snapshot position.&lt;/param&gt;</span>
    <span class="c1">/// &lt;returns&gt;&lt;see cref="bool"/&gt; Whether the snapshot was successfully added, as it was not duplicated.&lt;/returns&gt;</span>
    <span class="k">public</span> <span class="kt">bool</span> <span class="nf">TryAddSnapshot</span><span class="p">(</span><span class="n">SequenceNumber16</span> <span class="n">sequence</span><span class="p">,</span> <span class="n">Vector2</span> <span class="n">position</span><span class="p">)</span>
        <span class="p">=&gt;</span> <span class="k">this</span><span class="p">.</span><span class="nf">TryAddSnapshot</span><span class="p">(</span><span class="n">sequence</span><span class="p">,</span> <span class="n">position</span><span class="p">,</span> <span class="n">Time</span><span class="p">.</span><span class="nf">GetTicksUsec</span><span class="p">());</span>

    <span class="c1">/// &lt;summary&gt;</span>
    <span class="c1">/// Adds a snapshot to the interpolator.</span>
    <span class="c1">/// &lt;/summary&gt;</span>
    <span class="c1">/// &lt;param name="sequence"&gt;Snapshot sequence number.&lt;/param&gt;</span>
    <span class="c1">/// &lt;param name="position"&gt;Snapshot position.&lt;/param&gt;</span>
    <span class="c1">/// &lt;param name="currentTime"&gt;Current time in microseconds.&lt;/param&gt;</span>
    <span class="c1">/// &lt;returns&gt;&lt;see cref="bool"/&gt; Whether the snapshot was successfully added, as it was not duplicated.&lt;/returns&gt;</span>
    <span class="k">public</span> <span class="kt">bool</span> <span class="nf">TryAddSnapshot</span><span class="p">(</span><span class="n">SequenceNumber16</span> <span class="n">sequence</span><span class="p">,</span> <span class="n">Vector2</span> <span class="n">position</span><span class="p">,</span> <span class="kt">ulong</span> <span class="n">currentTime</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">this</span><span class="p">.</span><span class="nf">ThrowIfNotInitialized</span><span class="p">();</span>

        <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">ContainsKey</span><span class="p">(</span><span class="n">sequence</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">sequence</span><span class="p">,</span> <span class="n">position</span><span class="p">);</span>

        <span class="c1">// If just added snapshot is the second one</span>
        <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="n">Count</span> <span class="p">==</span> <span class="m">2</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c1">// Starts interpolation with a delay</span>
            <span class="k">this</span><span class="p">.</span><span class="n">firstSnapshotTime</span> <span class="p">=</span> <span class="n">currentTime</span> <span class="p">+</span> <span class="n">InterpolationStartDelay</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">/// &lt;summary&gt;</span>
    <span class="c1">/// Gets the interpolated position between snapshots for the current time, using &lt;see cref="Time.GetTicksUsec"/&gt; as a current time.</span>
    <span class="c1">/// &lt;/summary&gt;</span>
    <span class="c1">/// &lt;returns&gt;&lt;see cref="Vector2"/&gt; Interpolated position.&lt;/returns&gt;</span>
    <span class="k">public</span> <span class="n">Vector2</span> <span class="nf">GetInterpolatedPosition</span><span class="p">()</span>
        <span class="p">=&gt;</span> <span class="k">this</span><span class="p">.</span><span class="nf">GetInterpolatedPosition</span><span class="p">(</span><span class="n">Time</span><span class="p">.</span><span class="nf">GetTicksUsec</span><span class="p">());</span>

    <span class="c1">/// &lt;summary&gt;</span>
    <span class="c1">/// Gets the interpolated position between snapshots for the current time.</span>
    <span class="c1">/// &lt;/summary&gt;</span>
    <span class="c1">/// &lt;param name="currentTime"&gt;Current time in microseconds.&lt;/param&gt;</span>
    <span class="c1">/// &lt;returns&gt;&lt;see cref="Vector2"/&gt; Interpolated position.&lt;/returns&gt;</span>
    <span class="k">public</span> <span class="n">Vector2</span> <span class="nf">GetInterpolatedPosition</span><span class="p">(</span><span class="kt">ulong</span> <span class="n">currentTime</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">this</span><span class="p">.</span><span class="nf">ThrowIfNotInitialized</span><span class="p">();</span>

        <span class="k">while</span> <span class="p">(</span><span class="k">true</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="n">Count</span> <span class="p">==</span> <span class="m">1</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="c1">// If there's only 1 snapshot, use its position as-is.</span>
                <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">GetValueAtIndex</span><span class="p">(</span><span class="m">0</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">currentTime</span> <span class="p">&lt;=</span> <span class="k">this</span><span class="p">.</span><span class="n">firstSnapshotTime</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="c1">// Interpolation is currently delayed, use the first position.</span>
                <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">GetValueAtIndex</span><span class="p">(</span><span class="m">0</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">else</span>
            <span class="p">{</span>
                <span class="kt">ulong</span> <span class="n">secondSnapshotTime</span> <span class="p">=</span> <span class="k">this</span><span class="p">.</span><span class="nf">GetSecondSnapshotTime</span><span class="p">();</span>

                <span class="c1">// If overshoot the second,</span>
                <span class="k">if</span> <span class="p">(</span><span class="n">currentTime</span> <span class="p">&gt;</span> <span class="n">secondSnapshotTime</span><span class="p">)</span>
                <span class="p">{</span>
                    <span class="c1">// Remove the first snapshot, as it's no longer needed</span>
                    <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">RemoveAt</span><span class="p">(</span><span class="m">0</span><span class="p">);</span>
                    <span class="k">this</span><span class="p">.</span><span class="n">firstSnapshotTime</span> <span class="p">=</span> <span class="n">secondSnapshotTime</span><span class="p">;</span>

                    <span class="c1">// We have to check conditions from the start</span>
                    <span class="k">continue</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">else</span>
                <span class="p">{</span>
                    <span class="c1">// Calculate the weight of the interpolation</span>
                    <span class="kt">float</span> <span class="n">weight</span> <span class="p">=</span> <span class="p">(</span><span class="kt">float</span><span class="p">)((</span><span class="n">currentTime</span> <span class="p">-</span> <span class="k">this</span><span class="p">.</span><span class="n">firstSnapshotTime</span><span class="p">)</span> <span class="p">/</span> <span class="p">(</span><span class="kt">double</span><span class="p">)(</span><span class="n">secondSnapshotTime</span> <span class="p">-</span> <span class="k">this</span><span class="p">.</span><span class="n">firstSnapshotTime</span><span class="p">));</span>

                    <span class="n">Vector2</span> <span class="n">pos1</span> <span class="p">=</span> <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">GetValueAtIndex</span><span class="p">(</span><span class="m">0</span><span class="p">);</span>
                    <span class="n">Vector2</span> <span class="n">pos2</span> <span class="p">=</span> <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">GetValueAtIndex</span><span class="p">(</span><span class="m">1</span><span class="p">);</span>

                    <span class="c1">// Interpolate between 1st and 2nd positions</span>
                    <span class="k">return</span> <span class="n">pos1</span><span class="p">.</span><span class="nf">Lerp</span><span class="p">(</span><span class="n">pos2</span><span class="p">,</span> <span class="n">weight</span><span class="p">);</span>
                <span class="p">}</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">private</span> <span class="kt">ulong</span> <span class="nf">GetSecondSnapshotTime</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="n">Count</span> <span class="p">&lt;=</span> <span class="m">1</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nf">InvalidOperationException</span><span class="p">(</span><span class="s">"Second snapshot doesn't exist"</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="n">SequenceNumber16</span> <span class="n">seq1</span> <span class="p">=</span> <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">GetKeyAtIndex</span><span class="p">(</span><span class="m">0</span><span class="p">);</span>
        <span class="n">SequenceNumber16</span> <span class="n">seq2</span> <span class="p">=</span> <span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="nf">GetKeyAtIndex</span><span class="p">(</span><span class="m">1</span><span class="p">);</span>

        <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="n">firstSnapshotTime</span> <span class="p">+</span> <span class="p">((</span><span class="n">seq2</span> <span class="p">-</span> <span class="n">seq1</span><span class="p">).</span><span class="n">Number</span> <span class="p">*</span> <span class="n">SnapshotInterval</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">private</span> <span class="k">void</span> <span class="nf">ThrowIfNotInitialized</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">snapshots</span><span class="p">.</span><span class="n">Count</span> <span class="p">==</span> <span class="m">0</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nf">InvalidOperationException</span><span class="p">(</span><span class="s">$"SnapshotInterpolator is not initialized"</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p><em>마지막 수정 : 2025-06-30 15:39:00 +0900</em></p>]]></content><author><name>copyrat90</name></author><category term="Devlog" /><summary type="html"><![CDATA[플레이어 위치 동기화를 하기 위해, Snapshot Interpolation을 내 방식으로 구현했다.]]></summary></entry><entry><title type="html">Multi Plaza 개발일지 (01)</title><link href="https://copyrat90.github.io/2025/06/13/multi-plaza-devlog-01.html" rel="alternate" type="text/html" title="Multi Plaza 개발일지 (01)" /><published>2025-06-13T00:00:00+00:00</published><updated>2025-06-13T10:23:00+00:00</updated><id>https://copyrat90.github.io/2025/06/13/multi-plaza-devlog-01</id><content type="html" xml:base="https://copyrat90.github.io/2025/06/13/multi-plaza-devlog-01.html"><![CDATA[<p>올해 초부터 지금까지 작업 끝에 <a href="https://partner.steamgames.com/doc/features/multiplayer/steamdatagramrelay">Steam P2P Datagram Relay</a>를 경유한 채팅 구현까지 성공했다.</p>

<p>클라이언트 엔진은 Godot Engine을 사용 중이지만, 네트워킹 관련 코드는 <a href="https://partner.steamgames.com/doc/api/ISteamNetworkingSockets">ISteamNetworkingSockets</a> API를 기반으로 바닥부터 만드느라 시간이 꽤 걸렸다.</p>

<p>눈에 보이는 결과가 궁금할테니 일단 더미 테스트 영상부터 보여주고, 구현 내역 세부사항은 아래에 적도록 하겠다.</p>

<h1 id="채팅-테스트-영상">채팅 테스트 영상</h1>

<p><a href="https://www.youtube.com/watch?v=m29XLcMtsJs"><img src="https://img.youtube.com/vi/m29XLcMtsJs/hqdefault.jpg" alt="" /></a></p>

<p>그리고, 위 유튜브 동영상에는 안 나오지만 아래 이미지를 보면 2가지 추가기능이 있다.</p>

<p><img src="/assets/img/posts/2025-06-13-multi-plaza-devlog-01/chat-filter-test.png" alt="" /></p>

<ol>
  <li>지나치게 빠르게 채팅하면, 30초간 벙어리
    <ul>
      <li>기준: 10초 window에 5번 초과로 채팅</li>
    </ul>
  </li>
  <li><a href="https://store.steampowered.com/news/app/593110/view/2855803154584367415">Steam Chat Filtering</a> 이용한 욕설/비방 검열</li>
</ol>

<h2 id="대역폭-계산">대역폭 계산</h2>

<ul>
  <li>위 더미 테스트 영상에서, 각 클라이언트는 약 2초에 1개의 메시지를 보내고, 한번 채팅에 헤더 포함 평균 155 bytes의 메시지가 전송됨.
    <ul>
      <li>따라서, 각 클라이언트가 초당 약 77.5 bytes 정도 보낸다고 보면 됨.</li>
    </ul>
  </li>
  <li>로컬 클라이언트를 제외한 128명의 더미가, 로컬 클라이언트를 포함한 128명의 사용자에게 메시지를 보냄
    <ul>
      <li>따라서, 서버측에서는 초당 128 × 128 × 77.5 = 1,269,760 bytes 로, 1.21 MiB/s 정도의 broadcast가 필요함.</li>
    </ul>
  </li>
</ul>

<p>영상을 보면 초기에 안정적인 네트워크 상황일 때는 1.3 ~ 1.4 MiB/s 정도로 예측한 대역폭을 조금 웃돈다.<br />
하지만 Steam 소켓의 <a href="https://github.com/ValveSoftware/GameNetworkingSockets/blob/master/src/steamnetworkingsockets/clientlib/SNP_WIRE_FORMAT.md">SNP 헤더</a>와 암호화 오버헤드 등을 고려하면 그럴 수 있다 싶다.</p>

<p>중간에 네트워크 불안정으로 핑이 튀면서 전송량이 늘어나는 데,<br />
Steam 릴레이 서버 측 문제인지, 내 방이 무선 공유기에서 멀리 있는 탓인지 모르겠다.</p>

<h1 id="구현-내역">구현 내역</h1>

<p>연초부터 구현했던 내역을 돌아보자.</p>

<h2 id="1-gnssharp-라이브러리-구현">1. <a href="https://github.com/nalchi-net/GnsSharp">GnsSharp</a> 라이브러리 구현</h2>

<blockquote>
  <p>기존 C# Steamworks 바인딩인 <a href="https://github.com/rlabrecque/Steamworks.NET">Steamworks.NET</a>과 <a href="https://github.com/Facepunch/Facepunch.Steamworks">Facepunch.Steamworks</a> 둘 다 아쉬워서,<br />
바닥부터 다시 직접 만든 C# Steamworks 바인딩.</p>
</blockquote>

<ul>
  <li>Commit history: 2025.3.11 - 2025.5.3</li>
</ul>

<ol>
  <li>둘 다 오픈소스 버전 <a href="https://github.com/ValveSoftware/GameNetworkingSockets">GameNetworkingSockets</a>를 지원하지 않는 게 아쉬움.
    <ul>
      <li>내 라이브러리는 오픈소스 버전 GNS와, Steamworks SDK 버전을 모두 지원함.
        <ul>
          <li>그런데 현 프로젝트에는 Steamworks SDK 버전을 쓰고 있어서 당장은 무의미한 장점.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>둘 다 connection 별로 서로 다른 Connection Status Changed handler를 지정하는 것이 불가능함.
    <ul>
      <li>내 라이브러리는 connection 별로 서로 다른 handler 설정하도록 지원.
        <ul>
          <li>이게 있어야 서버 측과 클라이언트 측 코드를 깔끔하게 분리할 수 있음.</li>
          <li>GNS 쪽은 이게 자동으로 되는데 Steamworks SDK 쪽은 이게 기본적으로 안 돼서, 비슷하게 직접 구현함.
            <ul>
              <li>사용자가 connection에 <code class="language-plaintext highlighter-rouge">Marshal.GetFunctionPointerForDelegate()</code>로 등록한 함수 포인터를,<br />
<a href="https://github.com/nalchi-net/GnsSharp/blob/add303d893a5e912e81c7bef5eebe6401501ca63/GnsSharp/ISteamNetworkingSockets.cs#L1918">라이브러리 측에서 <code class="language-plaintext highlighter-rouge">Marshal.GetDelegateForFunctionPointer()</code>로 가져와서 호출하는 식</a>. 너무 hack인가?</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li>둘 다 오래된 라이브러리이다 보니 P/Invoke 인자로 managed 배열을 사용하는 게 아쉬움.
    <ul>
      <li>내 라이브러리는 <code class="language-plaintext highlighter-rouge">Span&lt;T&gt;</code>, <code class="language-plaintext highlighter-rouge">ReadOnlySpan&lt;T&gt;</code>를 사용하므로, <code class="language-plaintext highlighter-rouge">stackalloc</code> 배열을 인자로 넘겨 동적 할당을 피할 수 있음.</li>
    </ul>
  </li>
  <li>Facepunch.Steamworks는 API가 추상화되어 있어 <a href="https://partner.steamgames.com/doc/api">공식 Steamworks API Reference</a>를 이용하기 애매하고,<br />
 Steamworks.NET은 API가 1:1로 대응되나 <a href="https://partner.steamgames.com/doc/sdk/api#callbacks">Steam Callback과 CallResult</a> 처리가 C# 답지 못해서 아쉬움.
    <ul>
      <li>내 라이브러리는 API가 1:1로 대응되고, Steam Callback는 C# event로, Steam CallResult는 <a href="/2025/03/23/csharp-custom-awaitable">커스텀 awaitable 구현</a>으로 처리함.
        <ul>
          <li>내가 만든 커스텀 awaitable은 Facepunch.Steamworks와 달리:
            <ul>
              <li>lock을 걸고 Steam API call을 호출하여, <a href="/2025/03/23/csharp-custom-awaitable#사족-steamapicall_t로-calltaskt-찾기">비동기 요청이 Dictionary에 등록되기도 전에 반환되어 유실되는 race condition을 방지</a>.</li>
              <li><a href="https://github.com/nalchi-net/GnsSharp/blob/add303d893a5e912e81c7bef5eebe6401501ca63/GnsSharp/CallTask.cs#L59-L60">현재 SynchronizationContext를 capture해 <code class="language-plaintext highlighter-rouge">Post()</code></a>하므로, 동기화가 편리함.
                <ul>
                  <li>그게 필요없는 상황도 있을 테니, 추가로 <code class="language-plaintext highlighter-rouge">ConfigureAwait(false)</code>도 제공.</li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Facepunch.Steamworks는 poll group 단위로 메시지를 수신하는 게 불가능.
    <ul>
      <li>내 라이브러리는 원본 Steamworks SDK와 1:1 대응이므로 당연히 가능함.<br />
아마 Steamworks.NET도 가능할 텐데, 확인해보지는 않았다.</li>
    </ul>
  </li>
</ol>

<h2 id="2-nalchi--nalchisharp-라이브러리-구현">2. <a href="https://github.com/nalchi-net/nalchi">nalchi</a> / <a href="https://github.com/nalchi-net/NalchiSharp">NalchiSharp</a> 라이브러리 구현</h2>

<blockquote>
  <p>GameNetworkingSockets (Steamworks 소켓 부분) 의 전송 기능을 보강하는 C++23 라이브러리 및 그것의 C# 바인딩.</p>
</blockquote>

<ul>
  <li>
    <p>Commit history: 2025.3.2 - 2025.6.11</p>
  </li>
  <li>reference counting 되는 <a href="https://nalchi-net.github.io/nalchi/structnalchi_1_1shared__payload.html"><code class="language-plaintext highlighter-rouge">shared_payload</code></a>를 이용한 <a href="https://nalchi-net.github.io/nalchi/classnalchi_1_1socket__extensions.html"><code class="language-plaintext highlighter-rouge">socket_extensions::multicast()</code></a> 지원.
    <ul>
      <li>여러 클라이언트들에게 동일한 payload를 멀티캐스팅 할 시에, payload를 일일히 할당 -&gt; 복사하지 않고 다 같이 공유해 사용하기 위함.</li>
      <li>payload 포인터 <a href="/2025/02/24/gns-analysis-2#shared-payload">4바이트 앞 주소에 <code class="language-plaintext highlighter-rouge">std::atomic&lt;int&gt;</code>를 숨겨놓는 방식으로 구현</a>
        <ul>
          <li>이 ref count를 <a href="https://github.com/nalchi-net/nalchi/blob/168d1c5b1e93e0102a7e8c70bcb05b89c0504fe2/src/shared_payload.cpp#L154"><code class="language-plaintext highlighter-rouge">SteamNetworkingMessage_t::m_pfnFreeData</code>에 등록</a>한 <a href="https://github.com/nalchi-net/nalchi/blob/168d1c5b1e93e0102a7e8c70bcb05b89c0504fe2/src/shared_payload.cpp#L171-L178">커스텀 payload 해제 함수에서 사용해 해제 처리</a>.</li>
          <li>사용자 측 에러로 전송하지 못했을 경우를 대비한 <a href="https://nalchi-net.github.io/nalchi/structnalchi_1_1shared__payload.html#ae74e9f8d003554126f7f26e798c3e598"><code class="language-plaintext highlighter-rouge">shared_payload::force_deallocate()</code></a> 함수도 제공.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>비트 단위 직렬화 스트림 구현체 <a href="https://nalchi-net.github.io/nalchi/classnalchi_1_1bit__stream__writer.html"><code class="language-plaintext highlighter-rouge">bit_stream_writer</code></a>와 <a href="https://nalchi-net.github.io/nalchi/classnalchi_1_1bit__stream__reader.html"><code class="language-plaintext highlighter-rouge">bit_stream_reader</code></a> 제공.
    <ul>
      <li>공간 효율적인 직렬화를 통해 대역폭을 아끼기 위함.
        <ul>
          <li>예시: <code class="language-plaintext highlighter-rouge">enum</code> 값이 8종류 뿐이라면, <a href="https://nalchi-net.github.io/nalchi/classnalchi_1_1bit__stream__writer.html#a858b5ad5fa0974786709cbdbad85dc6e"><code class="language-plaintext highlighter-rouge">min = 0</code>, <code class="language-plaintext highlighter-rouge">max = 7</code>로 지정하면</a> 단 3비트만으로 직렬화가 됨.</li>
        </ul>
      </li>
      <li>Gaffer on Games 블로그 글을 참고해 구현하였음.
        <ul>
          <li><a href="https://gafferongames.com/post/reading_and_writing_packets/">https://gafferongames.com/post/reading_and_writing_packets/</a></li>
          <li><a href="https://gafferongames.com/post/serialization_strategies/">https://gafferongames.com/post/serialization_strategies/</a></li>
          <li>위 글대로 구현하면, 버퍼는 반드시 4바이트 단위로 읽기/쓰기가 가능해야 하므로, alignment를 고려해 <code class="language-plaintext highlighter-rouge">span&lt;std::uint32_t&gt;</code> 버퍼만 사용 가능하도록 제한.</li>
          <li>또한, <code class="language-plaintext highlighter-rouge">unicast()</code>와 <code class="language-plaintext highlighter-rouge">multicast()</code>로 <code class="language-plaintext highlighter-rouge">shared_payload</code>를 전송 시에, payload가 이 <code class="language-plaintext highlighter-rouge">bit_stream_writer</code>로 데이터를 썼으면,<br />
받는 측에서도 4바이트 단위로 읽어야 하므로, <code class="language-plaintext highlighter-rouge">bit_stream_reader</code>가 범위를 벗어난 읽기를 하는 것을 막기 위해 4의 배수의 byte 크기로 전송함.
            <ul>
              <li>이를 위해 <code class="language-plaintext highlighter-rouge">shared_payload</code>에는 <code class="language-plaintext highlighter-rouge">std::atomic&lt;int&gt;</code> ref count 말고도, <code class="language-plaintext highlighter-rouge">bit_stream_writer</code>를 사용했는지 체크하는 flag가 추가로 숨겨져 있음.</li>
            </ul>
          </li>
        </ul>
      </li>
      <li>추가로, 몇 비트 필요한지 크기를 재기 위한 <a href="https://nalchi-net.github.io/nalchi/classnalchi_1_1bit__stream__measurer.html"><code class="language-plaintext highlighter-rouge">bit_stream_measurer</code></a>도 제공.</li>
    </ul>
  </li>
  <li>Doxygen 이용한 <a href="https://nalchi-net.github.io/nalchi/">API 문서 제공</a>.</li>
</ul>

<h2 id="3-backdashgns-extension-라이브러리-구현">3. <a href="https://github.com/nalchi-net/Backdash.Gns">Backdash.Gns</a> extension 라이브러리 구현</h2>

<blockquote>
  <p>C# 오픈소스 롤백 넷코드 구현체인 <a href="https://github.com/lucasteles/Backdash">Backdash</a> 라이브러리를,<br />
내 <a href="https://github.com/nalchi-net/GnsSharp">GnsSharp</a> Steamworks 바인딩과 같이 쓸 수 있도록, 하부 네트워킹 레이어를 교체하는 extension</p>
</blockquote>

<ul>
  <li>
    <p>주요 작업일시: 2025.4.11 - 2025.4.30</p>
  </li>
  <li>Backdash는 <a href="https://github.com/pond3r/ggpo">GGPO</a>의 C# 버전 port로 시작했기 때문인지, Connection 개념이 따로 없는 UDP 기반 프로토콜을 사용함.
    <ul>
      <li>Connection 개념이 없다 =&gt; 매번 전송할 주소를 지정하도록 되어 있음. <code class="language-plaintext highlighter-rouge">ISteamNetworkingSockets</code>를 사용하기엔 다소 부적합.</li>
      <li>그래서 좀 더 “UDP 스러운” <a href="https://partner.steamgames.com/doc/api/ISteamNetworkingMessages"><code class="language-plaintext highlighter-rouge">ISteamNetworkingMessages</code> 인터페이스</a>를 대신 사용함.</li>
    </ul>
  </li>
  <li><a href="https://github.com/nalchi-net/BackdashGnsGodotSample">Backdash 예제 게임도 fork</a>해서 <a href="https://partner.steamgames.com/doc/features/multiplayer/matchmaking">Steam Lobby 시스템</a>을 이용하도록 만듦.</li>
</ul>

<h2 id="4-위-라이브러리들-기반으로-서버와-클라이언트-구현">4. 위 라이브러리들 기반으로 서버와 클라이언트 구현</h2>

<ul>
  <li>
    <p>주요 작업일시: 2025.4.21-2025.6.13</p>
  </li>
  <li>서버-클라이언트 부분은 별도의 C# 라이브러리로 분리.
    <ul>
      <li>Godot 프로젝트는 거기서 필요한 API를 사용하는 식.</li>
      <li>분리가 되었으므로, 더미 클라이언트는 Godot Engine을 안 쓰고 C# Console App으로 구현할 수 있었다.</li>
    </ul>
  </li>
  <li>서버와 클라이언트의 루프 처리 방법이 다름.
    <ul>
      <li>서버는 시작 시 10 tps로 도는 game loop용 <code class="language-plaintext highlighter-rouge">Task</code>를 스스로 생성해 돈다.
        <ul>
          <li>서버 라이브러리와 서버 컨텐츠 단을 별도 프로젝트로 분리하지 않았음.<br />
기획상 재사용의 여지가 별로 안 보였으므로, 하나로 합쳐서 단순하게 하기로 함.</li>
        </ul>
      </li>
      <li>클라이언트는 사용자 측에서 <code class="language-plaintext highlighter-rouge">WorldClient.PreTick()</code>과 <code class="language-plaintext highlighter-rouge">WorldClient.PostTick()</code>을 직접 호출해줘야 함.
        <ul>
          <li><code class="language-plaintext highlighter-rouge">PreTick()</code>에서 메시지 수신이, <code class="language-plaintext highlighter-rouge">PostTick()</code>에서 Steam socket 쪽에 보내둔 메시지의 실제 송신(flush)이 일어난다.
            <ul>
              <li>수동 flush 단계가 따로 있으므로, 아예 Nagle time은 <code class="language-plaintext highlighter-rouge">int.MaxValue</code>로 설정해놨다.
                <ul>
                  <li>그런데 Steamworks 로그 찍어보면 20 ms 로 설정된 것 같다. 저게 상한인 듯.</li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li>RPC 계층 구현
    <ul>
      <li>사실 그냥 위 nalchi 라이브러리의 bit stream을 이용한 수동 직렬화-역직렬화를 하고 있다.
        <ul>
          <li>직렬화 API 초기화 시 header &amp; footer 삽입
            <ul>
              <li>자세한 프로토콜은 비밀이지만, 두개 합쳐서 26 bits(무압축) 또는 52 bits(압축)로 8 bytes가 채 안 된다. 그런데 늘어날 여지가 있음.</li>
            </ul>
          </li>
          <li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.brotlistream?view=net-9.0"><code class="language-plaintext highlighter-rouge">BrotliStream</code></a> (<code class="language-plaintext highlighter-rouge">CompressionLevel.Fastest</code>) 이용한 압축 지원.
            <ul>
              <li>그런데 막상 써 보니 압축률이 너무 안 좋아서 거의 대부분의 자료를 무압축으로 전송하고 있음.<br />
사용자 리스트 직렬화하는데 800 bytes 이하면 압축시 크기가 오히려 불어나고, 2200 bytes 넘어도 압축률 겨우 10%…<br />
이미 비트 단위로 직렬화하고 있어서 압축이 더 될 구석이 없는건가?</li>
            </ul>
          </li>
          <li>코드 자동 생성같은 편의 기능은 없음.<br />
같은 메시지 type도 중간 데이터에 따라 후속 데이터가 가변으로 달라지는 경우가 있어서, codegen으로 처리하기가 애매한 측면이 있음.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>기타 스팀 관련 기능
    <ul>
      <li>스팀 로비 자동 열기 / 닫기</li>
    </ul>
  </li>
</ul>

<h3 id="설계도">설계도</h3>

<p>클래스를 기반으로 한 커뮤니케이션 다이어그램 형태에 가깝다.<br />
실제 구현은 아래 설계와 살짝 달라진 부분도 있긴 할 듯.</p>

<h4 id="worldserver"><code class="language-plaintext highlighter-rouge">WorldServer</code></h4>

<p><img src="/assets/img/posts/2025-06-13-multi-plaza-devlog-01/WorldServer.svg" alt="" /></p>

<h4 id="worldclient"><code class="language-plaintext highlighter-rouge">WorldClient</code></h4>

<p><img src="/assets/img/posts/2025-06-13-multi-plaza-devlog-01/WorldClient.svg" alt="" /></p>

<h1 id="여담">여담</h1>

<p>이렇게 많은 작업을 했는데 만든 게 겨우 채팅이라니… 혼자 만드려니 해야 할 작업이 정말 정말 많은 것 같다.<br />
그래도 이제 어느 정도 기반 작업은 마무리됐으니, 컨텐츠 작업에 들어갈 수 있다는 게 다행이다.</p>

<p><em>마지막 수정 : 2025-06-13 19:23:00 +0900</em></p>]]></content><author><name>copyrat90</name></author><category term="Devlog" /><summary type="html"><![CDATA[올해 초부터 지금까지 작업 끝에 Steam P2P Datagram Relay를 경유한 채팅 구현까지 성공했다.]]></summary></entry><entry><title type="html">Fight the Lag! The Trick Behind GGPO’s Low Latency Netcode (WIP)</title><link href="https://copyrat90.github.io/2025/04/09/ggpo-gdmag-article.html" rel="alternate" type="text/html" title="Fight the Lag! The Trick Behind GGPO’s Low Latency Netcode (WIP)" /><published>2025-04-09T00:00:00+00:00</published><updated>2025-04-10T05:06:00+00:00</updated><id>https://copyrat90.github.io/2025/04/09/ggpo-gdmag-article</id><content type="html" xml:base="https://copyrat90.github.io/2025/04/09/ggpo-gdmag-article.html"><![CDATA[<p>본 포스트는 <a href="https://drive.google.com/open?id=1cV0fY8e_SC1hIFF5E1rT8XRVRzPjU8W9">Tony Cannon의 <em>Fight the Lag! The Trick Behind GGPO’s Low Latency Netcode</em></a>를 한국어로 번역한 것입니다.<br />
This post is a Korean translation of the <a href="https://drive.google.com/open?id=1cV0fY8e_SC1hIFF5E1rT8XRVRzPjU8W9"><em>Fight the Lag! The Trick Behind GGPO’s Low Latency Netcode</em> by Tony Cannon</a>.</p>

<blockquote>
  <p>콘솔/PC에서 판매중인 명작 멀티플레이어 아케이드 게임들 몇몇은 온라인으로 플레이하면 랙 때문에 엉망이 된다.
그 이유는 간단하다. 정밀한 타이밍과 컨트롤이 중요한 게임을 하는 경우 (예를 들어 벨트스크롤 액션 게임<sub>brawlers</sub>, 슈팅 게임<sub>shoot’em-ups</sub>, 격투 게임<sub>fighting games</sub>), 최대한 랙이 없는 환경에서 하지 않는다면, 다들 자기 생각대로 제대로 플레이가 안 된다고 느낄 것이기 때문이다.
이 글에서는, 필자가 GGPO 넷코드<sub>netcode</sub> (“Good Game, Peace Out”의 약자) 를 어떻게 설계했는지를 다룰 것이다.
(GGPO는 <em>스컬걸즈</em>, <em>스트리트 파이터 3 서드 스트라이크 온라인 에디션</em>과, FinalBurn Alpha 에뮬레이터로 구동되는 수많은 아케이드 게임에 사용되었다.)
온라인 멀티플레이어에서의 랙을 숨기고 최소화하려는 개발자들에게 유용할 것이다. 특히 실력이 타이밍으로 좌우되는 게임에 말이다.</p>

  <p>GGPO는 이하 조건을 만족하는 모든 아케이드 스타일 게임에 적용할 수 있다: 1) 모든 게임 시뮬레이션 상태의 업데이트는 오로지 이전 시뮬레이션 상태와 플레이어 입력에 의해 결정론적<sub>deterministically</sub>으로 이루어져야 하고, 2) 컨트롤러 입력, 화면 렌더링, 오디오와는 별개로 시뮬레이션 상태를 업데이트할 수 있어야 하며, 3) 필요시 시뮬레이션 상태를 저장하고 복원할 수 있어야 한다.
이 모든 조건을 만족한다면 나머지 세부 사항은 GGPO가 책임진다.
게임 개발자는 그저 게임 루프를 수정해 추측 기반 실행<sub>speculative execution</sub>을 허용하기만 하면 된다.</p>
</blockquote>

<h1 id="identifying-the-checkpoint">Identifying the checkpoint</h1>

<p>멀티플레이어 게임에 온라인 지원을 추가하는 제일 흔한 방법은 각 기기에서 시뮬레이션을 돌리되, 각 시뮬레이션이 완전히 똑같은 입력을 받도록 하여 동기화를 유지하는 방법이다.</p>

<figure style=";padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="/assets/img/posts/2025-04-09-ggpo-gdmag-article/fig1.svg" width="802px" />
<figcaption aria-hidden="true">그림 1: 전통적인 프레임 지연<sub>frame-delay</sub> 방식의 네트워크 플레이 구현.</figcaption>
</figure>

<p>시뮬레이션이 오로지 입력에 의해서만 결정<sub>determined</sub>된다면, 양쪽 기기에서 같은 입력을 하는 것으로 같은 결과를 재현할 수 있다.
이 방법은 장점이 많다.
컴퓨터는 태생적으로 결정론적이고 대부분의 아케이드 게임이 이미 정수 연산만을 수행한다. (정수 연산은 서로 다른 프로세서 간에도 보통 같은 결과를 도출한다.)
이를 통해 개발자는 네트워크 구현의 세부 사항으로부터 완전히 분리될 수 있다.
게임이 결정론적으로 수행되도록 하는 문제는 제쳐두면, 게임플레이를 구현하는 엔지니어와 디자이너들은 네트워크 엔진의 세부 사항과는 분리되어 작업할 수 있다.
이 말은 이미 출시된 게임에 온라인 멀티플레이어를 차후에 추가<sub>retroactively add</sub>할 수 있다는 말이다.
(게임이 작성되었던 원본 하드웨어의 에뮬레이터를 제공한다면, 심지어 게임을 재컴파일 할 필요도 없다!)
마지막 장점은, 이 방식은 단순한 매치메이킹<sub>matchmaking</sub> 서비스를 제외하면 서버를 운영할 필요가 없다는 점이다.
그리고 보통 이런 서비스는 콘솔 제조사에서 제공한다.</p>

<p>안타깝게도, 이 방식은 큰 단점<sub>major drawback</sub>도 하나 있다.
보통 이런 게임은 각 시뮬레이션 업데이트 전에 컨트롤러 입력을 읽어오도록 설계되어 있다는 점이다.
모든 원격<sub>remote</sub> 플레이어의 입력을 받아오기 전까지는 1프레임의 시뮬레이션을 수행할 수 없다.
실제 게임에서, 이는 한 기기에서 다른 기기로 패킷<sub>packet</sub>을 전송하는 데 걸리는 시간 만큼의 입력 지연<sub>input delay</sub>의 모습으로 나타난다.
한마디로, 게임이 랙 걸린다.
게임이 의도한 빠릿한 반응속도는 느릿하고 지척거리는<sub>sluggish and squishy</sub> 조작감으로 대체되어, 플레이어의 경험을 망가뜨린다.</p>

<p>많은 경우, 네트워크 계층에 의해 발생한 지연은 게임의 느낌을 완전히 바꿔버리고 만다.
<em>스트리트 파이터</em> 팬들이 흔히 “랙 전략<sub>lag tactics</sub>“이라 부르는, 상대가 내 기술을 볼 시점이면 반응하기엔 늦었다는 점을 이용한 플레이가 가능하다.
나를 포함해 많은 사람에게, 랙 전략은 온라인 대전 경험<sub>competitive experience</sub>에 지대한 영향을 미친다.</p>

<p>필자는 이 방식의 장점은 그대로 취하면서, 랙 문제를 더 잘 해결하기 위해 GGPO를 작성했다.
시뮬레이션 전체에 입력 지연을 추가하는 대신, GGPO는 각 원격 플레이어의 행동 시작 선딜<sub>start-up of each remote player’s action</sub>에 연결의 지연 시간을 감춤으로써 로컬 플레이어 아바타의 즉각적인 반응을 보장한다.
이 방식이 온라인 매치에서 오프라인의 경험을 충실히 재현하는데 더 성공적이다.</p>

<h1 id="the-solution-ggpo">The Solution: GGPO</h1>

<p>GGPO는 로컬 플레이어가 느끼는<sub>perceived</sub> 입력 지연을 추측 기반 실행<sub>speculative execution</sub>을 이용해 제거한다.
플레이어의 시뮬레이션 프레임을 실행하기 전에 모든 입력이 도착하기를 기다리는 대신, GGPO는 기존 행동을 토대로 원격 플레이어가 무엇을 할지를 예측한다.</p>

<figure style=";padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="/assets/img/posts/2025-04-09-ggpo-gdmag-article/fig2.svg" width="802px" />
<figcaption aria-hidden="true">그림 2: GGPO의 예측 메커니즘 뜯어보기</figcaption>
</figure>

<p>전통적인 프레임 지연<sub>frame-delay</sub> 방식을 사용했을 때 로컬 플레이어가 느끼는 랙이 위 방법으로 제거된다.
로컬 플레이어 아바타의 반응성이 오프라인 플레이와 똑같아진다<sub>just as responsive</sub>.
비록 입력이 도착할 때까지 다른 플레이어의 행동을 알 수는 없지만, GGPO의 예측 메커니즘이 게임 시뮬레이션이 대부분의 시간 동안 올바른 것을 보장한다.</p>

<p>GGPO가 네트워크에서 원격 입력을 받으면, 예측된 입력과 실제 입력을 비교한다.
불일치<sub>discrepancy</sub>가 발견되면, GGPO는 시뮬레이션을 최초로 틀린 프레임으로 되감고<sub>rewind back</sub>, 업데이트된 입력 스트림을 토대로 각 플레이어의 입력을 재예측한 후, 새로운 예측을 토대로 현재 프레임까지 시뮬레이션을 진행시킨다.</p>

<figure style=";padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="/assets/img/posts/2025-04-09-ggpo-gdmag-article/fig3.svg" width="826px" />
<figcaption aria-hidden="true">그림 3: GGPO가 동작하는 모습. 1프레임에서의 롤백<sub>rollback</sub>에 유의할 것.</figcaption>
</figure>

<h1 id="hiding-the-lag">Hiding the lag</h1>

<p>GGPO에서는, 로컬 플레이어의 행동은 항상 즉각적으로 적용되고, 언제나 올바르다.
이는 좋은 특성인데, 컨트롤러 입력에 대한 아바타의 반응성이 보통 온라인 플레이를 즐기는 데 있어서 가장 중요한 측면이기 때문이다.</p>

<p>더군다나, 이미 수신된 원격 플레이어 입력으로 인한 장기적인 효과도 올바르다.
예를 들어, <em>스트리트 파이터</em>에서 상대가 몇 프레임 전에 파동권<sub>fireball</sub>을 썼다면, 그 기탄<sub>fireball</sub>의 움직임은 완전히 결정론적이고 상대 플레이어의 후속 입력에 의해 전혀 영향받지 않는다.
그러므로, 로컬 시뮬레이션 상태상 플레이어가 파동권을 쐈다고 확정되는<sub>determined</sub> 그 직후부터 기탄의 움직임은 항상 올바르게 보일 것이다.
그에 따라 파동권 타이밍과 그것에 대응하는 느낌<sub>experience</sub>이 온라인이건 오프라인이건 똑같아진다.
이는 중요한데, 파동권에 대응하는 것이 <em>스트리트 파이터</em>의 주된 플레이 요소<sub>major part</sub> 중 하나이기 때문이다!</p>

<p>비슷하게, 적은 보통 점프 이후 그 궤적<sub>arc</sub>을 바꿀 수 없으므로, 적이 점프 후 하강할 때, 이를테면 잘 잰 승룡권<sub>well-paced Dragon Punch</sub>을 꽂아주는 등의 대응도 온·오프라인 막론하고 똑같을 것이다.
그런데 모든 게 항상 잘 작동하는 것처럼 보인다면, 지연 시간<sub>latency</sub>은 어디로 간 걸까?</p>

<p>지연 시간<sub>latency</sub>은 적이 행동을 개시하는 시점과 로컬 시뮬레이션이 그것을 인지하는 시점 사이에 숨겨져 있다.
그 사이 간격<sub>window</sub>의 손실된 시간은 시뮬레이션에서 건너뛰어진 셈<sub>effectively skipped</sub>이다.
예를 들어, 당신과 적이 패킷을 보내는 데 60ms가 걸리는 네트워크 상에서 <em>스트리트 파이터</em>를 하고 있다고 해 보자.
적이 기술을 사용한 시점에, 적의 시뮬레이션은 컨트롤러 입력을 즉시 처리한다.
적에게는, 기술이 바로 나오는 것으로 보인다. 로컬 입력은 시뮬레이션으로 즉시 보내지고 항상 올바르기 때문이다.
하지만, 당신 시뮬레이션 측에서는, 해당 입력을 담은 패킷이 도착하는 다음 60ms 동안 적이 기술을 사용했다는 것을 알 방법이 없다.
패킷이 도착하면, GGPO는 게임을 60ms 되감고, 적의 입력을 보정한 후, 게임 시뮬레이션을 60ms 빨리감기<sub>fast-forward</sub>해 현재 시간으로 되돌려놓는다.
그 결과, 당신의 기기에서는 적 행동 첫 60ms 동안의 애니메이션을 볼 수 없다.
당신 관점에서는 마치 적 애니메이션이 이미 60ms 재생된 시점부터 시작하는 걸로 보인다.</p>

<p>이는 이상적이지는 않지만, 다른 대안은 로컬 입력을 포함해 시뮬레이션 전체를 60ms 지연시키는 것뿐이다.
실제로 적용해 보면, 60ms의 애니메이션 손실이 훨씬 더 나은<sub>greatly preferable</sub> 사용자 경험을 낳는다.
이것은 부분적으로는 로컬 입력 반응성이 훨씬 좋아진 덕분이기도 하지만, 대부분의 경우 60ms가 그저 중요하지 않기 때문이기도 하다.
이를 설명하기 위해, 구체적인 사례를 들어 살펴보자.</p>

<p><em>스트리트 파이터</em>의 공격 대부분은 3단계<sub>phases</sub>로 이루어진다: 선딜<sub>start-up</sub>, 공격<sub>execution</sub>, 그리고 후딜<sub>recovery</sub>이 그것이다.</p>

<figure style=";padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="/assets/img/posts/2025-04-09-ggpo-gdmag-article/fig4.svg" width="852px" />
<figcaption aria-hidden="true">그림 4: 대부분의 광대역<sub>broadband</sub> 연결에서, GGPO는 스트리트 파이터 기술의 랙을 선딜 단계<sub>start-up phase</sub>에 숨길<sub>mask</sub> 수 있다.</figcaption>
</figure>

<p>기술의 선딜<sub>start-up</sub>은 유저가 버튼을 누른 후 실제 공격 판정이 생기기까지 걸리는 시간을 말한다.
선딜<sub>start-up</sub> 단계에서도 보통 애니메이션은 있지만, 기술이 실제로 데미지를 입히지는 않는다.
진짜 중요한 일<sub>serious business</sub>은 공격 단계<sub>execution window</sub>에서 벌어진다.
공격 단계에서 적이 당신 공격의 판정 범위<sub>active region</sub>와 겹쳐 있다면, 게임 시뮬레이션이 타격<sub>hit</sub>했다고 판정<sub>register</sub>할 것이다.
타격이 발생하면 시뮬레이션은 새로운 애니메이션과 효과음을 재생하고, 적의 체력을 일정량 깎는 등의 여러 효과를 적용시킨다.
시뮬레이션 상태에 관한 한 이는 대단히 중요한 일이다.
후딜<sub>Recovery</sub>은 공격 단계 이후 다음 기술을 쓸 수 있을 때까지의 시간 간격이다.</p>

<p>이 수치들은 보통 프레임<sub>frame</sub> 단위로 측정되는데, 신작이 출시되면 프로 <em>스트리트 파이터</em> 플레이어들<sub>competitive players</sub>이 가장 먼저 하는 일은 전술 연구를 위해 모든 기술의 프레임 데이터를 추출<sub>mine</sub>하는 일이다.
<em>스트리트 파이터</em> 시리즈 중 가장 사랑받고 또 빠른 <em>슈퍼 스트리트 파이터 2 터보</em>의 <a href="https://zachd.com/nki/ST/flame.html">프레임 데이터</a>를 보면, 대부분의 기술들이 최소한 4프레임(66ms)의 선딜<sub>start-up</sub>이 있음을 볼 수 있다.
이 사실이 굉장히 중요하다.
왜냐면 이 말은 120ms 핑<sub>ping</sub>짜리 연결에서, 거의 모든 기술의 롤백이 공격 단계<sub>execution</sub>에 들어가기 전에 해결될 수 있다는 말이고, 이는 잘못된 예측으로 인한 그래픽과 사운드 글리치<sub>visual and audio glitches</sub>가 거의 항상 선딜<sub>start-up</sub> 애니메이션에서만 발생하고, 적을 때려서 발생하는 경우는 거의 없다는 말이다.</p>

<p>현대의 로스앤젤레스와 뉴욕을 잇는 광대역<sub>broadband</sub> 연결은 일반적으로 120ms보다는 빠른 핑<sub>ping</sub>을 갖는다.
사실, GGPO의 테크닉이 세계를 잇는 광대역 연결에서의 지연까지도 잘 커버한다는<sub>scale well up to</sub> 실사례 증거<sub>anecdotal evidence</sub>도 있다.
<strong>그림 5</strong>를 보면 <a href="https://www.ggpo.net/">GGPO.net</a> 운영 당시 전형적이었던 저녁 시간대 테스트 서버 활동량 시각화 이미지<sub>snapshot</sub>를 볼 수 있다.</p>

<figure style=";padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="/assets/img/posts/2025-04-09-ggpo-gdmag-article/fig5.svg" width="852px" />
<figcaption aria-hidden="true">그림 5: <a href="https://www.ggpo.net/">GGPO.net</a> 테스트 서버 활동량 시각화 이미지. 보다시피, 대륙간 플레이도 문제가 되지 않았었다.</figcaption>
</figure>

<h1 id="integrating-ggpo">Integrating GGPO</h1>

<p>GGPO는 개발자가 네트워크 세부 사항으로부터 최대한 격리될 수 있도록 작성되었다.
<strong>그림 6</strong>은 아케이드 게임에서의 단순화된 게임 루프를 표현한 것이다.</p>

<figure style=";padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="/assets/img/posts/2025-04-09-ggpo-gdmag-article/fig6.svg" width="306px" />
<figcaption aria-hidden="true">그림 6: 전형적인 아케이드 게임 루프.</figcaption>
</figure>

<p>게임 루프는 컨트롤러로부터 샘플링<sub>samples</sub>을 수행해 다음 게임 시뮬레이션 상태에 사용할 입력을 생성한다.
그 입력은 시뮬레이션 엔진으로 전달돼 게임을 다음 프레임으로 업데이트하고 각 시뮬레이션 단계의 결과를 렌더링<sub>render</sub>한다.
타이밍이 중요한<sub>timing-sensitive</sub> 많은 아케이드 게임은 게임 루프를 고정된 속도<sub>fixed rate</sub>로 (예: 60hz) 돌리는데<sub>drive their game-loop</sub>, 그런 경우 다음 프레임을 위해 다음 컨트롤러 상태를 샘플링하기 전, 대기<sub>idle</sub>하는 것이 필요할 수 있다.
이 게임 루프에는 다양한 변형<sub>many variations</sub>이 존재한다.
예를 들어, 어떤 게임은 컨트롤러 샘플링과 게임 업데이트를 30hz로 수행하지만, 최근 2개의 게임 상태를 보간<sub>interpolating</sub>하여 120hz로 렌더링될 수 있다.
GGPO는 이런 상황에서도 마찬가지로 적용할 수 있다.</p>

<figure style=";padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="/assets/img/posts/2025-04-09-ggpo-gdmag-article/fig7.svg" width="639px" />
<figcaption aria-hidden="true">그림 7: GGPO를 쓰는 아케이드 게임 루프. GGPO와 통합하기 위해 추가/수정된 단계는 회색 블록으로 표현하였다.</figcaption>
</figure>

<p><strong>그림 7</strong>은 GGPO를 통합<sub>incorporate</sub>하기 위해 변형된 게임 루프를 보여준다.
컨트롤러에서 샘플링을 수행한 다음, 개발자는 그 입력을 <code class="language-plaintext highlighter-rouge">ggpo_synchronize_inputs</code> 함수를 통해 GGPO에 전달해야 한다.
<code class="language-plaintext highlighter-rouge">ggpo_synchronize_inputs</code>은 모든 로컬 입력을 원격 플레이어에게 전송할 것이다.
또한 이 함수는 모든 원격 플레이어의 예측된 입력과 실제 입력을 병합하여 입력 스트림에 기록한다.
결과물은 각 플레이어의 입력으로 이루어진 튜플<sub>tuple</sub>로, 이를 로컬 게임 엔진에 전달할 수 있다.</p>

<p>개발자는 게임 엔진의 대부분<sub>bulk</sub>을 수정하지 않은 채로 놔둘 수 있다.
이후에 언급할 잠재적 주의사항<sub>potential caveats</sub> 몇개만 빼면 말이다.
게임 루프의 처음으로 돌아가기 전에 대기<sub>idling</sub>하는 대신, 개발자는 <code class="language-plaintext highlighter-rouge">ggpo_advance_frame</code> 함수를 호출해야 한다.
이 함수는 모든 원격 플레이어로부터 받은 입력을 예측한 값과 비교한다.
불일치<sub>discrepancy</sub>가 발견되면, <code class="language-plaintext highlighter-rouge">ggpo_advance_frame</code>은 마지막으로 올바르게 예측한 프레임을 불러온 후, 올바르게 고친<sub>corrected</sub> 입력을 가지고 게임의 상태 업데이트 함수를 반복 호출하여 게임 시뮬레이션을 현재 프레임까지 빨리감기<sub>fast-forward</sub>한다.
로드<sub>load</sub>, 저장<sub>save</sub>, 실행<sub>execute</sub> 함수들은 GGPO 초기화 시 개발자가 제공한다.</p>

<h1 id="synchronizing-the-clock-and-inputs">Synchronizing the clock and inputs</h1>

<p>GGPO는 세션 내 플레이어 간 입력을 동기화하는데<sub>synchronizing inputs</sub> 단순하고 효율적인 프로토콜을 사용한다.</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="nc">packet</span> <span class="p">{</span>
    <span class="k">struct</span> <span class="p">{</span>
        <span class="n">uint16</span>  <span class="n">magic</span><span class="p">;</span>
        <span class="n">uint8</span>   <span class="n">type</span><span class="p">;</span>
    <span class="p">}</span> <span class="n">hdr</span><span class="p">;</span>
    <span class="k">union</span> <span class="p">{</span>
        <span class="k">struct</span> <span class="p">{</span>
            <span class="n">uint32</span>  <span class="n">start_frame</span><span class="p">;</span>
            <span class="n">uint32</span>  <span class="n">ack_frame</span><span class="p">;</span>
            <span class="n">uint16</span>  <span class="n">num_bits</span><span class="p">;</span>
            <span class="n">uint8</span>   <span class="n">bits</span><span class="p">[</span><span class="n">MAX_COMPRESSED_BITS</span><span class="p">];</span>
        <span class="p">}</span> <span class="n">input</span><span class="p">;</span>
        <span class="k">struct</span> <span class="p">{</span>
            <span class="n">int8</span>    <span class="n">frame_advantage</span><span class="p">;</span>
            <span class="n">uint32</span>  <span class="n">ping</span><span class="p">;</span>
        <span class="p">}</span> <span class="n">quality_report</span><span class="p">;</span>
        <span class="k">struct</span> <span class="p">{</span>
            <span class="n">uint32</span>  <span class="n">pong</span><span class="p">;</span>
        <span class="p">}</span> <span class="n">quality_reply</span><span class="p">;</span>
    <span class="p">}</span> <span class="n">u</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>
<blockquote>
  <p>코드 1: GGPO가 사용하는 UDP 패킷 페이로드<sub>payload</sub>를 단순화한 버전<sub>simplified description</sub>.<br />
(역자 주: 실제 버전은 <a href="https://github.com/pond3r/ggpo/blob/master/src/lib/ggpo/network/udp_msg.h">GGPO 소스 코드의 <code class="language-plaintext highlighter-rouge">udp_msg.h</code></a>를 참고할 것.)</p>
</blockquote>

<p>각 패킷의 헤더에는 16비트 세션별 식별자<sub>session-specific identifier</sub>가 들어있고, 그 뒤에 전달할 데이터의 타입<sub>type of the payload</sub>이 붙는다.
3가지의 주요 패킷 타입은 <code class="language-plaintext highlighter-rouge">quality_report</code>, <code class="language-plaintext highlighter-rouge">quality_reply</code>와, <code class="language-plaintext highlighter-rouge">input</code>이다.</p>

<p>매번 <code class="language-plaintext highlighter-rouge">ggpo_synchronize_inputs</code>를 호출할 때마다 입력 페이로드 1개가 전송된다.
가상 버튼을 껐다 켰다<sub>toggle</sub>하는 상태 기계<sub>state machine</sub>를 이용해 입력이 압축된다.
상태 기계는 0프레임에는 비어있는 입력 벡터<sub>empty input vector</sub>로 시작한다.
각 프레임마다 이전 프레임과 달라진 버튼 입력을 비트 배열<sub>bits array</sub> 안에 인코딩하는데, 아래의 꽤나 원시적인 인코딩 방식<sub>fairly trivial coding system</sub>을 사용한다:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1 + &lt;N의 5비트&gt; : 이전 입력의 버튼 N을 toggle (반전)
0 : 입력 끝
</code></pre></div></div>
<p>스트림 내의 거의 모든 입력이 한개의 비트 (0) 로 압축된다.
초당 10회 넘는 입력이 있는 극도로 까딱거리는<sub>twitchy</sub> 게임에서조차 초당 300비트 정도로 압축된다.
이는 충분히 작기 때문에 이전에 승인된<sub>acknowledged</sub> 프레임의 모든 입력<sub>all inputs</sub>을 모든 패킷<sub>every packet</sub>에 인코딩한다.
이렇게 하면 유실<sub>dropped</sub>되거나 순서가 뒤섞인<sub>out-of-order</sub> 패킷에 대한 처리가 아주 간단해진다.
GGPO는 원격 플레이어로부터 받은 마지막 x번째까지의 입력 이력<sub>history of the last x inputs</sub>을 보관하고 있는데, 여기서 x는 예측 배리어<sub>prediction barrier</sub>보다 더 큰 범위<sub>window</sub>이다.
원격 플레이어로부터 입력을 수신할 때마다, 이 범위<sub>window</sub>로부터 <code class="language-plaintext highlighter-rouge">start_frame</code>의 입력을 불러온 후 비트 상태 기계를 실행해 모든 후속 입력을 복원한다.
우리 범위<sub>window</sub>를 넘어서는 입력들을 생성하는 경우, 그 입력들은 예측 시스템<sub>prediction subsystem</sub>으로 보내져 검증<sub>verification</sub>을 거친 후 범위<sub>window</sub>에 저장된다.
끝으로, 마지막으로 생성된 입력의 수를 기억함으로써, 그것을 다음 입력 패킷의 <code class="language-plaintext highlighter-rouge">ack_frame</code> 필드에 포함해 상대에게 보낼 수 있도록 한다.</p>

<p>GGPO는 주기적으로 <code class="language-plaintext highlighter-rouge">quality_report</code> 패킷을 보내 연결의 공정성<sub>fairness</sub>을 측정한다.
매 품질 측정<sub>quality-report</sub> 패킷은 현재 기기에서 생성한 타임스탬프<sub>timestamp</sub>와, 현재 피어<sub>peer</sub> 자신의 로컬 “프레임 어드밴티지<sub>frame advantage</sub>” 측정값을 포함한다.
상대방<sub>peer</sub>이 <code class="language-plaintext highlighter-rouge">quality_report</code> 메시지를 받으면, 받은 즉시 report 내에 있는 <code class="language-plaintext highlighter-rouge">ping</code> 값을 복사해 <code class="language-plaintext highlighter-rouge">quality_reply</code> 응답을 보낸다.
본래 발신했던 피어<sub>originating peer</sub>는 현재 시간에서 마지막 <code class="language-plaintext highlighter-rouge">quality_reply</code> 패킷의 <code class="language-plaintext highlighter-rouge">pong</code> 값을 빼서 왕복 시간<sub>round-trip time</sub>을 측정한다.</p>

<p>GGPO에서 “프레임 어드밴티지”란 로컬 플레이어가 시간 왜곡<sub>wall clock skew</sub>으로 인해 몇 프레임의 어드밴티지를 갖는지를 나타낸다.
이는 다음 공식으로 계산된다:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>frame_advantage = (last_remote_frame + (ping * frame_frequency / 2)) - last_local_frame
프레임_어드밴티지 = (마지막_원격_프레임 + (핑 * 프레임_빈도 / 2)) - 마지막_로컬_프레임
</code></pre></div></div>
<p>다시 말해, 상대가 현재 렌더링하는 프레임을 우리가 마지막으로 받은 패킷에 왕복 시간<sub>round-trip time</sub>의 절반을 더하고, 거기서 우리가 렌더링하는 프레임을 빼서 추정하는 것이다.
그 결과는 상대방이 우리보다 앞서 있는 프레임의 수다.
예를 들어, 우리가 <code class="language-plaintext highlighter-rouge">frame_advantage</code>를 2라고 계산했다 해보자.
이 말은 두 게임으로부터 동일한 거리만큼 떨어진<sub>equidistant</sub> 제3자<sub>neutral observer</sub>가 보기에 내 게임이 20프레임을 렌더링중이라면 같은 순간 상대방은 22프레임을 렌더링중이라는 말이다.
GGPO는 이것을 “유리한 것<sub>advantage</sub>“으로 간주하는데 그 이유는 우리 시뮬레이션은 상대에 비해 2프레임 덜 롤백해도 되기 때문이다.
그 말은 상대 게임 세계가 이쪽보다 평균적으로 더 많이 만료됐다는<sub>out-of-date</sub> 의미이다.
프레임 어드밴티지를 계산함에 있어서 오차를 유발할 가능성이 있는 것들이 많기는 하다.
이를테면 비대칭적 패킷 전송 시간<sub>asymmetric packet transmit times</sub>이나, 간헐적인 연결 문제<sub>intermittent connection issues</sub> 등이 있을 수 있다.
하지만 실제로 써보면 위 공식으로도 잘 작동하는 것으로 보인다.</p>

<p>GGPO 세션에서의 각 피어는 언제나 자신의 로컬 프레임 어드밴티지를 알고 있으며 상대방이 계산한 프레임 어드밴티지도 주기적으로 수신한다.
GGPO는 로컬과 원격의 프레임 어드밴티지를 1프레임 내의 허용 오차<sub>tolerance</sub>로 조정하여<sub>agree to</sub> 게임을 가능한 한 “공정하게<sub>fair</sub>” 유지하려고 한다.
예를 들어, GGPO 종단<sub>endpoint</sub>이 로컬 프레임 어드밴티지를 계속 5라고 계산하는데, 상대방의 로컬 프레임 어드밴티지는 계속 3이라면, GGPO는 로컬 종단의 실행을 1프레임 늦춤으로써 이 차이<sub>disparity</sub>를 평준화<sub>equalize</sub>하려고 할 것이다.
그 결과 로컬 단말<sub>local end</sub>은 1프레임을 잃고 원격 단말<sub>remote end</sub>은 1프레임을 얻어, 양측의 프레임 어드밴티지가 4프레임으로 평준화된다.
로컬 종단을 어떻게 느리게 만드는지는 게임 개발자가 제공하는 콜백<sub>callback</sub> 구현에 따라 달라진다.</p>

<h1 id="separating-game-state-from-rendering">Separating Game State from Rendering</h1>

<p>이제 왜 GGPO가 게임 로직과 렌더링을 분리할 것을 요구하는지 명확해졌으리라 생각한다.
각 장면<sub>video frame</sub>의 렌더링마다, 잘못 예측한 원격 입력 탓에 현재 상태를 재평가하느라 게임 상태를 여러번 업데이트해야 할 수도 있기 때문이다.
만일 게임 엔진이 게임 상태 재평가에 더해 그 중간 장면까지 렌더링해야 한다면, GGPO의 롤백 테크닉은 감히 엄두도 못 낼 정도로 오래 걸리는<sub>prohibitively expensive</sub> 작업일 것이다.
예를 들어, 비디오 렌더러<sub>video renderer</sub>는 온갖 역운동학<sub>inverse kinematics</sub>, 소프트바디 시뮬레이션<sub>soft body simulation</sub>, 그리고 시각효과<sub>visual effect</sub>를 위한 기타 비싼<sub>expensive</sub> 연산을 수행할 지도 모르는데, GGPO를 쓰려면 게임 시뮬레이션시 이런 연산이 필요 없도록 처리해야 할 것이다.</p>

<p>게임 렌더러는 또한 잘못 예측된 이전 프레임에서 자원<sub>assets</sub>을 제거할 수 있어야 한다.
예를 들어, 기탄<sub>fireball</sub>을 발사하며 효과음을 낸 프레임이 상대 입력을 받아보니 올바른 결과가 아닐 수 있다.
이 상황은 그래픽<sub>video</sub>에 대해서는 처리하기 쉽지만, 사운드<sub>audio</sub>에 대해서는 까다로울 수 있다.
오디오를 처리하기 위해 사용된 방법 중 2가지가 성공적이었다.</p>

<p>첫번째는 오디오를 시뮬레이션 상태로 취급하는 방법이다.
게임 상태가 초당 30회 업데이트된다면, 각 채널<sub>channel</sub>마다 33.3ms의 사운드<sub>audio</sub> 샘플을 포함해 게임 상태와 같이 재생<sub>render</sub>하면 된다.
효과음<sub>audio</sub>을 재생할 때, 전체를 재생하는 게 아니라 33.3ms만을 재생한다.
이 방법은 비교적 구현하기 쉽지만, 긴 롤백 도중 터지는 소리<sub>audio popping</sub>를 유발할 수 있다.</p>

<p>두번째 방법은 게임 상태 안에 이전에 재생한 모든 효과음과 재생한 시점을 기억해 놓는 방법이다.
저장 간격<sub>window</sub>은 GGPO에 설정된 최대 버퍼 간격<sub>maximum buffer window</sub>만큼만 크면 된다.
효과음<sub>audio</sub>을 재생할 때, 게임 상태 내의 효과음 리스트를 현재 오디오 장치에서 대기 중인<sub>queued</sub> 효과음들과 비교한다.
게임 상태에는 있으나 대기 중<sub>queued</sub>이지 않은 효과음들은 오디오 장치로 전송돼야 한다.
효과음이 롤백 도중에 일어났다면 몇 밀리초 이후 시점부터 재생해야 할 수도 있다.
(이런 경우 볼륨을 0%부터 시작해 서서히 100%로 높이는 것이 터지는 소리<sub>popping effect</sub>를 완화<sub>alleviate</sub>하는 데 도움이 될 수 있다.)
오디오 대기열<sub>audio queue</sub>에는 있으나, 시뮬레이션 상태에는 없는 효과음들의 경우는, 롤백의 결과로 취소된<sub>revoked</sub> 것들이다.
애초에 재생한 것이 잘못이므로 멈춰야 하는데, 갑작스러운 변화<sub>popping</sub>를 막기 위해 볼륨을 몇 프레임에 걸쳐 0%까지 감쇠<sub>attenuating</sub>시켜야 할 수도 있다.</p>

<h1 id="getting-it-all-right-the-first-time">Getting It All Right the First Time</h1>

<p>GGPO SDK는 아주 사용하기 쉽지만, 매우 복잡한 게임이나, GGPO를 고려하지 않고 설계·작성된 게임은, 여러 장벽<sub>stumbling blocks</sub>에 봉착할 수 있다.
첫번째 문제는 금방 다뤘다: 그래픽과 사운드 렌더링<sub>video and audio renderers</sub>이 게임 시뮬레이션 상태와는 분리되어야<sub>divorced</sub> 한다는 점이다.
두번째는, 각 프레임마다 시뮬레이션 업데이트 단계를 여러번 수행하기에 충분한 CPU 시간<sub>budget</sub>이 있음을 게임 개발자가 보장해야 한다는 것이다.
이상적으로는, 게임 시뮬레이션이 프레임당 4~5번 돌 수 있도록 충분히 빠르면 좋은데, 이러면 대략 80ms의 지연 시간을 감출 수 있다.
마지막으로, 게임 시뮬레이션이 완전히 결정론적이고, 오로지 플레이어 입력에 의해서만 결정되어야 한다는 점이다.</p>

<p>로컬 멀티플레이어의 경우 모든 입력이 100% 올바르고 로컬 컨트롤러에서 즉각 들어오므로 롤백을 할 이유가 전혀 없다.
그 결과, 이 3가지 기능은 거의 항상 게임의 네트워킹 부분을 테스트할 때나 구현할 때만 테스트된다.
이는 보통 게임에 투자되는 전체 테스트 시간 대비 아주 작은 시간<sub>small fraction</sub>에 불과하다.</p>

<p>GGPO로 게임을 포팅<sub>port</sub>하려는 개발자들을 돕기 위해, GGPO에는 “동기화 테스트<sub>sync test</sub>“라 불리는 특수한 디버깅 모드가 포함되어 있다.
GGPO를 동기화 테스트<sub>sync test</sub> 모드로 초기화하면, SDK는 모든 게임 프레임을 원격 입력이 잘못 예측된 프레임으로 간주한다. 이는 로컬 플레이를 하더라도 마찬가지로 적용된다.
<code class="language-plaintext highlighter-rouge">ggpo_advance_frame</code>을 호출할 때마다 항상 프레임이 불러와지고, 설정된 수만큼 다시 실행되며, 게임 상태도 저장될 것이다.
이를 이용하면 가장 어려운 부분의 성능<sub>performance</sub>과 정확성<sub>correctness</sub>이 네트워크나 원격 세션 없이 구현·디버깅될 수 있으므로, GGPO를 통합하는 개발 및 테스트 시간이 현격히 줄어들 것이다.</p>

<p>랙이라는 몬스터를 잡는<sub>slaying the lag monster</sub> 완벽한 해결책<sub>silver bullet</sub>은 없지만, GGPO는 게임 개발자들에게 그것과 씨름해 항복을 받아낼<sub>wrestling it into submission</sub> 또 다른 도구를 제공한다.
GGPO와 함께라면, 개발자들은 게임 루프나 엔진 설계를 복잡하게 만들지 않고도 게임의 입력 지연을 한쪽으로 패킷을 전송하는 시간<sub>one-way packet transmission time</sub> 미만으로 줄일 수 있다.
아케이드 게임 문화에 깊은 뿌리를 둔 사람의 입장으로서 말하건데, 세상의 개발자들이 GGPO나 이 글에서 설명한 테크닉을 가지고 랙 없는 온라인 게임 타이틀을 만들어가길 희망한다.</p>

<hr />

<p><em>Tony Cannon은 1995년 Stanford University에서 컴퓨터 과학에 대한 학사 학위를 취득하며 졸업했다.</em>
<em>그는 VXtreme Inc., Microsoft에서 일했었고, 현재는 VMware와 Radiant Entertainment에서 일하고 있다.</em>
<em>Tony는 격투 게임에 대한 열정이 있고 Evolution Tournament Series의 공동 설립자이자 토너먼트 디렉터이기도 하다.</em></p>

<hr />

<h1 id="부록">부록</h1>

<h2 id="testing-ggpo-with-emulators">Testing GGPO With Emulators</h2>

<p>(WIP)</p>

<h2 id="ggpos-prediction-algorithm">GGPO’s prediction algorithm</h2>

<p>(WIP)</p>

<p><em>마지막 수정 : 2025-04-10 14:06:00 +0900</em></p>]]></content><author><name>Tony Cannon</name></author><category term="Netcode" /><summary type="html"><![CDATA[본 포스트는 Tony Cannon의 Fight the Lag! The Trick Behind GGPO’s Low Latency Netcode를 한국어로 번역한 것입니다. This post is a Korean translation of the Fight the Lag! The Trick Behind GGPO’s Low Latency Netcode by Tony Cannon.]]></summary></entry><entry><title type="html">Fast-Paced Multiplayer (Part IV) - Lag Compensation</title><link href="https://copyrat90.github.io/2025/04/06/fast-paced-multiplayer-4.html" rel="alternate" type="text/html" title="Fast-Paced Multiplayer (Part IV) - Lag Compensation" /><published>2025-04-06T00:00:00+00:00</published><updated>2025-04-06T01:41:00+00:00</updated><id>https://copyrat90.github.io/2025/04/06/fast-paced-multiplayer-4</id><content type="html" xml:base="https://copyrat90.github.io/2025/04/06/fast-paced-multiplayer-4.html"><![CDATA[<p>본 포스트는 <a href="https://www.gabrielgambetta.com/lag-compensation.html">Gabriel Gambetta의 <em>Fast-Paced Multiplayer (Part IV): Lag Compensation</em></a>를 한국어로 번역한 것입니다.<br />
This post is a Korean translation of the <a href="https://www.gabrielgambetta.com/lag-compensation.html"><em>Fast-Paced Multiplayer (Part IV): Lag Compensation</em> by Gabriel Gambetta</a>.</p>

<p>시리즈의 다른 글 링크:</p>
<ol>
  <li><a href="/2025/04/05/fast-paced-multiplayer-1">Client-Server Game Architecture</a></li>
  <li><a href="/2025/04/05/fast-paced-multiplayer-2">Client-Side Prediction and Server Reconciliation</a></li>
  <li><a href="/2025/04/05/fast-paced-multiplayer-3">Entity Interpolation</a></li>
  <li>Lag Compensation (현재 글)</li>
  <li><a href="https://www.gabrielgambetta.com/client-side-prediction-live-demo.html">Live Demo</a></li>
</ol>

<h1 id="introduction">Introduction</h1>

<p>이전 3개 글에서 아래와 같이 요약할 수 있는 클라이언트-서버 게임 구조에 대해 다뤘다.</p>
<ul>
  <li>서버는 모든 클라이언트로부터 시간 정보<sub>timestamp</sub>를 포함한 입력을 받는다</li>
  <li>서버는 입력을 처리하고, 월드 상태를 업데이트한다</li>
  <li>서버는 모든 클라이언트에게 평범한 월드 스냅샷<sub>regular world snapshots</sub>을 보낸다</li>
  <li>클라이언트는 입력을 보내고 그 효과를 로컬에서 시뮬레이션한다</li>
  <li>클라이언트가 월드 업데이트를 받으면
    <ul>
      <li>예측된 상태를 승인된<sub>authoritative</sub> 상태로 동기화한다<sub>syncs</sub></li>
      <li>다른 개체들에 대해서는, 알려진 과거 상태들을 가지고 보간<sub>interpolates</sub>한다</li>
    </ul>
  </li>
</ul>

<p>플레이어의 관점에서, 이는 2개의 중요한 결과를 야기한다:</p>
<ul>
  <li>플레이어는 <strong>자기 자신</strong>을 <strong>현재 모습</strong>으로 본다</li>
  <li>플레이어는 <strong>다른 개체</strong>들을 <strong>과거 모습</strong>으로 본다</li>
</ul>

<p>이런 상황은 일반적으로 문제가 없지만, 시간, 공간적으로 민감한 사건에 대해서는 꽤 골치아픈 문제가 생긴다.
예를 들어, 적의 머리를 사격하는 상황에서 말이다!</p>

<h1 id="lag-compensation">Lag Compensation</h1>

<p>저격총으로 목표물의 머리를 완벽히 정조준하고 있다.
탕! 절대 빗나갈 수가 없는 한발이다.</p>

<p>그런데 빗나간다.</p>

<p>왜 빗나갔을까?</p>

<p>전에 설명했던 클라이언트-서버 아키텍처 때문에, 적 머리의 <em>현 위치</em>가 아닌, 100 ms <em>이전</em>에 있었던 위치에 대고 조준하고 있는 것이다!</p>

<p>어찌 보면, 게임을 빛의 속도가 아주 느린 우주에서 플레이하고 있다고 볼 수 있다.
적의 과거 위치를 보면서 조준하고 있으나, 방아쇠를 당기기 오래 전에 적은 이미 다른 곳으로 이동한 것이다.</p>

<p>다행히, <em>대부분의</em> 플레이어가 <em>대체로</em> 만족하는 비교적 간단한 해결책이 있다.
(만족하지 않는 1가지 사례는 아래에서 살펴볼 것이다.)</p>

<p>원리를 설명하자면 이렇다:</p>
<ul>
  <li>총을 발사할 때, 클라이언트는 시간 정보<sub>timestamp</sub>, 조준 위치를 포함한 전체 이벤트 정보를 서버로 송신한다.</li>
  <li><strong>가장 중요한 단계다.</strong> 서버가 모든 입력을 시간 정보와 함께 받으므로, 과거 어떤 시점의 월드든 정확하게<sub>authoritatively</sub> 재현할 수 있다.
구체적으로 말하면, 특정 클라이언트가 어떤 시점에 보는 월드 상태를 정확하게 재현할 수 있다.</li>
  <li>이 말은, 서버가 유저가 총을 쏘던 시점에 시야에 있던 목표물을 정확히 알 수 있다는 말이다.
목표물은 적 머리의 <em>과거</em> 위치였지만, 서버는 그게 <em>해당 유저</em> 입장에서 현재 위치였음을 알 수 있다.</li>
  <li>서버가 사격을 <em>그 시점 기준으로</em> 처리하고, 클라이언트를 업데이트한다.</li>
</ul>

<p>이제 모두가 행복해졌다!</p>

<p>서버는 서버이기 때문에 언제나 그렇듯 행복하다.</p>

<p>총을 쏜 유저는 적의 머리를 조준, 사격하고, 짜릿한<sub>rewarding</sub> 헤드샷을 맞춰서 행복하다.</p>

<p>적은 그닥 행복하지 않은 유일한 사람이다.
가만히 있다가 맞았다면, 자기 잘못이겠지?
움직이고 있다가 맞았으면… 우와, 총 쏜 사람이 대단한 저격수였나보네.</p>

<p>하지만 적이 노출된 위치에 있다가, 벽 뒤로 안전하게 숨고, <em>그 뒤에</em> 총에 맞는다면 어떨까?</p>

<p>그런 일이 실제로 발생할 수 있다.
그것이 이 해결책을 사용한 대가<sub>tradeoff</sub>이다.
과거의 적을 사격할 수 있게 되었기 때문에, 은폐를 했다고 해도 몇 밀리초 동안은 총에 맞을 가능성이 생긴다.</p>

<p>약간의 부조리는 있지만, 그래도 이것이 모두가 동의할 만한 가장 합리적인 해결책이다.
빗나갈 수가 없는 사격이 빗나간다면 그게 훨씬 나쁠 테니까!</p>

<h1 id="conclusion">Conclusion</h1>

<p>빠른 호흡의 멀티플레이어 게임에 관한 시리즈는 이걸로 끝이다.
이런 것은 확실히 제대로 만들기 쉽지 않지만, 정확한 개념적 이해가 있다면, 불가능할 정도로 어려운 건 아니다.</p>

<p>작성한 글의 대상 독자는 게임 개발자들이었지만, 게이머들도 흥미롭게 읽을 수 있겠다!
게이머의 관점에서 왜 어떤 일이 그렇게 벌어지는 지를 이해하는 것은 흥미로울 테니.</p>

<h2 id="further-reading">Further Reading</h2>

<p>여기서 다뤘던 테크닉들은 꽤나 영리하지만, 필자가 만든 것이 아니다.
필자가 작성한 글은 다른 글, 소스 코드와 같은 외부 매체와 약간의 실험을 통해 필자가 배운 것을 그저 이해하기 쉽게 정리한 가이드에 불과하다.</p>

<p>이 주제에 관련된 읽어볼만한 글은 <a href="https://gafferongames.com/post/what_every_programmer_needs_to_know_about_game_networking/">What Every Programmer Needs to Know About Game Networking</a>과 <a href="https://developer.valvesoftware.com/wiki/Latency_Compensating_Methods_in_Client/Server_In-game_Protocol_Design_and_Optimization">Latency Compensating Methods in Client/Server In-game Protocol Design and Optimization</a>이 있다.</p>

<p><a href="/2025/04/05/fast-paced-multiplayer-3">« Part III: Entity Interpolation</a> · <strong><a href="https://www.gabrielgambetta.com/client-side-prediction-live-demo.html">Live Demo »</a></strong></p>

<p><em>마지막 수정 : 2025-04-06 10:41:00 +0900</em></p>]]></content><author><name>Gabriel Gambetta</name></author><category term="Netcode" /><summary type="html"><![CDATA[본 포스트는 Gabriel Gambetta의 Fast-Paced Multiplayer (Part IV): Lag Compensation를 한국어로 번역한 것입니다. This post is a Korean translation of the Fast-Paced Multiplayer (Part IV): Lag Compensation by Gabriel Gambetta.]]></summary></entry><entry><title type="html">Fast-Paced Multiplayer (Part I) - Client-Server Game Architecture</title><link href="https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-1.html" rel="alternate" type="text/html" title="Fast-Paced Multiplayer (Part I) - Client-Server Game Architecture" /><published>2025-04-05T00:00:00+00:00</published><updated>2025-04-06T00:12:00+00:00</updated><id>https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-1</id><content type="html" xml:base="https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-1.html"><![CDATA[<p>본 포스트는 <a href="https://www.gabrielgambetta.com/client-server-game-architecture.html">Gabriel Gambetta의 <em>Fast-Paced Multiplayer (Part I): Client-Server Game Architecture</em></a>를 한국어로 번역한 것입니다.<br />
This post is a Korean translation of the <a href="https://www.gabrielgambetta.com/client-server-game-architecture.html"><em>Fast-Paced Multiplayer (Part I): Client-Server Game Architecture</em> by Gabriel Gambetta</a>.</p>

<p>시리즈의 다른 글 링크:</p>
<ol>
  <li>Client-Server Game Architecture (현재 글)</li>
  <li><a href="/2025/04/05/fast-paced-multiplayer-2">Client-Side Prediction and Server Reconciliation</a></li>
  <li><a href="/2025/04/05/fast-paced-multiplayer-3">Entity Interpolation</a></li>
  <li><a href="/2025/04/06/fast-paced-multiplayer-4">Lag Compensation</a></li>
  <li><a href="https://www.gabrielgambetta.com/client-side-prediction-live-demo.html">Live Demo</a></li>
</ol>

<h1 id="introduction">Introduction</h1>

<p>이 글은 빠른 호흡의 멀티플레이어 게임을 가능토록 하는 테크닉과 알고리즘을 알아보는 시리즈의 첫번째 글이다.
멀티플레이어 게임의 기본 개념에 익숙하다면, 다음 글로 바로 넘어가도 된다. 이번 글은 서론에 해당한다.</p>

<p>게임을 만드는 것 자체가 쉽지 않은 일이다.
허나, 멀티플레이어 게임을 만드려면 완전히 새로운 차원의 문제를 풀어야 한다.
흥미롭게도, 문제의 핵심은 인간 본성과 물리학에 있다.</p>

<h1 id="the-problem-of-cheating">The problem of cheating</h1>

<p>모든 게 치트 문제<sub>cheating</sub>로부터 시작된다.</p>

<p>게임 개발자로서, 싱글 플레이어 게임에서의 치트<sub>cheat</sub>는 큰 관심거리가 아니다.
치터<sub>cheating player</sub> 자기 혼자에게만 적용되고, 다른 사람에게는 영향이 없으므로.
물론 치터는 게임을 의도된 대로 경험하진 못할 수 있다.
그러나 치터 자신의 게임이므로, 자기가 원하는 방식으로 즐길 권리가 있는 것이다.</p>

<p>하지만 멀티플레이어 게임의 경우는 다르다.
어떤 대전 게임이든, 치터는 자기 게임을 좋게 만드는 것을 넘어, 다른 유저의 게임을 나쁘게 만든다.
치팅은 플레이어가 게임을 떠나게 만드므로, 개발자는 이를 막을 대책을 강구해야 할 것이다.</p>

<p>치트를 막기 위한 수많은 방법이 있으나, 가장 중요한 방법 (그리고 거의 유일하게 의미 있는 방법) 은 단순하다.
<em>플레이어를 믿지 마라.</em>
항상 최악의 상황을 상정하라.
즉, 플레이어들은 <em>치팅을 시도할 것</em>이라 생각하라.</p>

<h1 id="authoritative-servers-and-dumb-clients">Authoritative servers and dumb clients</h1>

<p>이는 언뜻 보기에 간단한 해법으로 연결된다.
게임 내 모든 행동을 우리가 관리하는 중앙 서버에서만 일어나도록 하고, 클라이언트들은 그저 게임의 관찰자로 만드는 해법이 그것이다.
달리 말해, 클라이언트는 입력 (버튼 눌림, 명령 등) 만을 서버에 전송하고, 서버가 게임을 돌리고, 그 결과를 클라이언트에게 돌려주는 것이다.
이는 보통 <em>authoritative server<sub>권위 있는 서버</sub></em> 방식이라 부르는데, 월드에서 일어나는 모든 일에 대한 최종 승인권을 서버가 갖기 때문이다.</p>

<p>물론, 서버 취약점으로 인한 치트가 발생할 수 있으나, 그건 본 시리즈의 범위를 벗어난다.
그래도, authoritative server를 사용하면 수많은 핵을 막을 수 있다.
예를 들어, 플레이어의 HP를 판단할 때 클라이언트를 믿지 않는다.
조작된 클라이언트는 자기 플레이어의 HP값을 10000%라고 변조할 수 있지만, 서버는 사실 10%밖에 없음을 <em>알고 있다</em>.
조작된 클라이언트가 뭐라 생각하든, 플레이어는 피격당하면 바로 죽을 것이다.</p>

<p>서버는 또한 플레이어의 월드상 위치도 믿지 않는다.
조작된 클라이언트는 서버에게 <strong>“내 위치는 (10,10)”</strong>이라 말하고 1초 뒤에 <strong>“내 위치는 (20,10)”</strong>이라 말할 수 있다.
이걸 믿었다면, 벽을 뚫거나 다른 플레이어보다 빠르게 이동해버릴 수 있다.
그 대신, 서버는 플레이어가 (10,10)에 있음을 <em>알고 있고</em>, 클라이언트가 서버에게 <strong>“나 오른쪽으로 1칸 이동하고 싶어”</strong>라고 말하게 한다.
서버는 내부 상태를 업데이트해 플레이어 위치를 (11,10)으로 만들고, 플레이어에게 <strong>“네 위치는 (11,10)”</strong>이라고 회신한다.</p>

<figure style="background-color:#777777;padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="https://www.gabrielgambetta.com/img/fpm1-01.png" style="background-color:#777777" />
<figcaption aria-hidden="true"><i>단순한 클라이언트-서버 상호작용.</i></figcaption>
</figure>

<p>요약하면, 게임 상태는 서버만이 유일하게 관리한다.
클라이언트는 자신의 행동을 서버에 전송한다.
서버는 게임 상태를 주기적으로 업데이트하며, 새로운 게임 상태를 클라이언트에게 보내고, 클라이언트는 이를 단순히 화면에 렌더링만<sub>render</sub> 한다.</p>

<h1 id="dealing-with-networks">Dealing with networks</h1>

<p>위에서 다룬 dumb client<sub>멍청한 클라이언트</sub> 방식은 전략 게임이나 포커 같은 느린 턴제 게임에 대해서는 잘 동작한다.
LAN 환경에서도 동작할 것이다. 통신이 즉각적이므로.
하지만 네트워크를 경유하는 빠른 호흡의 게임에 이 방식을 적용하려고 하면 동작하지 않을 것이다.</p>

<p>물리학에 대해 이야기해보자. 샌프란시스코에서 뉴욕에 있는 서버에 접속한다고 해 보자. 이는 대략 4,000 km 이다. (참고로 서울-부산 사이 거리가 400 km 정도 된다.)
그 어떤 것도 빛보다 빠르게 이동할 수 없고, 인터넷을 통한 바이트 전송도 예외는 아니다. (통신도 빛의 pulse, 회선 내의 전자<sub>electron</sub>, 혹은 전자기파로 이루어지는 것이다.)
빛은 대략 시속 300,000 km 이므로, 4,000 km를 이동하는 데는 13 ms 가 소요된다.</p>

<p>꽤 빠르다고 생각할 수 있으나, 이건 실제로는 아주 낙관적인 상황의 예측이다.
데이터가 빛의 속도로 직진한다는 가정이고, 보통의 경우 그렇지 않을 것이다.
현실에서는, 데이터가 라우터와 라우터를 거치며 여러 번의 점프 (네트워크 용어로는 hop이라고 부른다) 를 한다.
이는 빛의 속도로 이루어지지 않는다.
라우터에서 데이터가 복사, 검사, 재라우팅 되기 때문에 다소간 지연이 발생한다.</p>

<p>논의를 위해, 클라이언트에서 서버로 전송되기까지 50 ms 가 걸린다고 해 보자.
이것은 거의 최선의 상황이다.
뉴욕에서 도쿄로 연결한다면 어떨까?
모종의 이유로 네트워크가 혼잡하다면?
100 ms, 200 ms, 심지어 500 ms 의 지연도 발생하는 경우가 있다.</p>

<p>우리 예시로 돌아와서, 클라이언트가 서버에게 <strong>“나 오른쪽 방향키 눌렀어”</strong>라고 보낸다 하자.
서버는 이걸 50 ms 뒤에 받는다.
서버가 이 요청을 받는 즉시 처리해서 업데이트된 상태를 보낸다 치자.
클라이언트가 새로운 게임 상태 메시지 <strong>“네 위치는 (1,0)”</strong>을 받는데 50 ms 가 추가로 소요된다.</p>

<p>플레이어 관점에서 보면, 오른쪽 방향키를 눌렀는데 0.1초 동안 아무런 반응이 없는 것으로 보인다.
그런 이후에야 캐릭터가 오른쪽으로 1칸 이동한다.
이 <em>랙<sub>lag</sub></em>이 얼마 안 돼 보일지 모르지만, 생각보다 알아차리기 쉽다.
그리고 당연히, 0.5초의 랙은 알아채기 쉬운 정도가 아니라, 아예 게임 플레이를 불가능하게 만든다.</p>

<h1 id="summary">Summary</h1>

<p>네트워크 멀티플레이어 게임은 아주 재밌지만, 완전히 새로운 차원의 문제를 야기한다.
Authoritative server 구조는 대부분의 치트를 방지하지만, 이걸 그대로 구현하면 게임의 반응성이 떨어진다.</p>

<p>앞으로의 글에서는, authoritative server를 기반으로 하되, 플레이어가 느끼는 지연을 최소화하여,
로컬 멀티플레이나 싱글 플레이와 구분이 거의 불가능할 정도의 시스템을 만드는 방법을 살펴보도록 하겠다.</p>

<p><strong><a href="/2025/04/05/fast-paced-multiplayer-2">Part II: Client-Side Prediction and Server Reconciliation »</a></strong></p>

<p><em>마지막 수정 : 2025-04-06 09:12:00 +0900</em></p>]]></content><author><name>Gabriel Gambetta</name></author><category term="Netcode" /><summary type="html"><![CDATA[본 포스트는 Gabriel Gambetta의 Fast-Paced Multiplayer (Part I): Client-Server Game Architecture를 한국어로 번역한 것입니다. This post is a Korean translation of the Fast-Paced Multiplayer (Part I): Client-Server Game Architecture by Gabriel Gambetta.]]></summary></entry><entry><title type="html">Fast-Paced Multiplayer (Part II) - Client-Side Prediction and Server Reconciliation</title><link href="https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-2.html" rel="alternate" type="text/html" title="Fast-Paced Multiplayer (Part II) - Client-Side Prediction and Server Reconciliation" /><published>2025-04-05T00:00:00+00:00</published><updated>2025-04-06T00:12:00+00:00</updated><id>https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-2</id><content type="html" xml:base="https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-2.html"><![CDATA[<p>본 포스트는 <a href="https://www.gabrielgambetta.com/client-side-prediction-server-reconciliation.html">Gabriel Gambetta의 <em>Fast-Paced Multiplayer (Part II): Client-Side Prediction and Server Reconciliation</em></a>를 한국어로 번역한 것입니다.<br />
This post is a Korean translation of the <a href="https://www.gabrielgambetta.com/client-side-prediction-server-reconciliation.html"><em>Fast-Paced Multiplayer (Part II): Client-Side Prediction and Server Reconciliation</em> by Gabriel Gambetta</a>.</p>

<p>시리즈의 다른 글 링크:</p>
<ol>
  <li><a href="/2025/04/05/fast-paced-multiplayer-1">Client-Server Game Architecture</a></li>
  <li>Client-Side Prediction and Server Reconciliation (현재 글)</li>
  <li><a href="/2025/04/05/fast-paced-multiplayer-3">Entity Interpolation</a></li>
  <li><a href="/2025/04/06/fast-paced-multiplayer-4">Lag Compensation</a></li>
  <li><a href="https://www.gabrielgambetta.com/client-side-prediction-live-demo.html">Live Demo</a></li>
</ol>

<h1 id="introduction">Introduction</h1>

<p>시리즈의 <a href="/2025/04/05/fast-paced-multiplayer-1">첫번째 글</a>에서, authoritative server와 dumb client를 사용한 클라이언트-서버 모델을 살펴보았다.
이는 클라이언트는 단순히 입력만을 서버에 전송하고, 서버로부터 업데이트된 게임 상태를 받으면 렌더링만을<sub>render</sub> 하는 방식이다.</p>

<p>이 방식을 순진하게<sub>naive</sub> 구현하면 유저의 명령과 화면의 변화 사이에 지연 시간을 야기한다.
예를 들어, 플레이어가 오른쪽 방향키를 누르면, 캐릭터가 이동을 시작하는 데까지 0.5초가 걸릴 수 있다.
그 이유는 클라이언트의 입력이 서버까지 전송되고, 서버가 입력을 처리하고 새로운 게임 상태를 연산한 후, 업데이트된 게임 상태가 클라이언트까지 돌아와야 하기 때문이다.</p>

<figure style="background-color:#777777;padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="https://www.gabrielgambetta.com/img/fpm2-01.png" style="background-color:#777777" />
<figcaption aria-hidden="true"><i>네트워크 지연의 결과.</i></figcaption>
</figure>

<p>인터넷과 같이 수십~수백 밀리초의 지연이 발생할 수 있는 네트워크 환경에서, 이 방식은 좋은 경우에도 반응성이 낮게 느껴지며, 최악의 경우에는 전혀 플레이가 불가능 할 수 있다.
이번 글에서는, 이 문제를 최소화하거나 아예 없애버리는 방법을 찾아보도록 하겠다.</p>

<h1 id="client-side-prediction">Client-side prediction</h1>

<p>비록 치터들<sub>cheating players</sub>이 있긴 하지만, 대부분의 시간 동안 게임 서버는 정상적인 요청을 처리한다 (정상 클라이언트의 모든 요청과 치터가 치트를 안 쓰는 때의 요청).
이는 들어오는 입력 대부분이 정상이고 게임 상태를 예측한 대로 업데이트 시킨다는 말이다.
그 말은, 캐릭터가 (10,10)에 있는 상태에서 오른쪽 방향키를 눌렀다면, (11,10)으로 이동할 것이라는 의미다.</p>

<p>이 점을 이용할 수 있다.
게임 월드가 충분히 <em>결정론적<sub>deterministic</sub></em>이라면 (다시 말해, 주어진 게임 상태와 입력에 대해, 결과를 완벽히 예측할 수 있다면),
입력을 서버에 전송하는 <em>즉시</em> 클라이언트에서 입력을 처리할 수 있다.
이 말은, 서버가 입력을 처리하여 만들 게임 상태를 클라이언트 측에서 <em>예측</em>한다는 말이다.
이를 통해 입력을 하고 나서 그 효과를 렌더링하기까지의 지연 시간을 제거할 수 있다.
게다가, 대부분의 경우 이 예측은 정확할 것이므로, 서버가 업데이트된 게임 상태를 전송하고 나서도 시각적인 불일치<sub>visible mismatch</sub>가 발생하는 경우는 없을 것이다.</p>

<p>예를 들어 100 ms 랙<sub>lag</sub>이 있고, 캐릭터가 다음 칸으로 이동하는 애니메이션이 100 ms 가 걸린다고 해보자.
순진한<sub>naive</sub> 구현에서, 전체 동작은 200 ms 가 소요될 것이다:</p>

<figure style="background-color:#777777;padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="https://www.gabrielgambetta.com/img/fpm2-02.png" style="background-color:#777777" />
<figcaption aria-hidden="true"><i>네트워크 지연 + 애니메이션.</i></figcaption>
</figure>

<p>월드가 결정론적이므로, 서버에 전송한 입력이 성공적으로 실행될 거라 가정할 수 있다.
이 가정 하에서, 클라이언트는 입력이 처리된 뒤의 게임 상태를 예측할 수 있고, 대부분의 경우 이 예측은 맞아떨어질 것이다.</p>

<p>입력을 보낸 후 게임 상태가 오길 기다렸다가 렌더링하는 대신, 입력을 보내자마자 성공했다고 가정하고 결과를 렌더링할 수 있다.
그 사이에 “진짜<sub>true</sub>” 게임 상태가 도착하고, 보통의 경우, 로컬 측에서 계산한 결과와 일치할 것이다:</p>

<figure style="background-color:#777777;padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="https://www.gabrielgambetta.com/img/fpm2-03.png" style="background-color:#777777" />
<figcaption aria-hidden="true"><i>서버가 행동을 확인하는 동안 애니메이션이 재생된다.</i></figcaption>
</figure>

<p>이제 플레이어의 행동과 화면상 결과 사이에 지연이 전혀 없으면서, 서버는 여전히 authoritative하다.
(만일 조작된 클라이언트가 비정상적인 입력을 보낸다면, 자기 화면에는 자기 마음대로 렌더링하겠지만,
서버의 상태에는 영향을 미치지 못할 것이며, 다른 플레이어에게는 보이지 않을 것이다.)</p>

<h1 id="synchronization-issues">Synchronization issues</h1>

<p>위 예시에서, 필자는 모든 게 잘 작동하는 수치를 세심하게 골랐다.
그러나, 약간 변형된 시나리오를 생각해보자.
서버와의 사이에 250 ms 랙이 있고, 다음 칸으로 이동하는 데 100 ms 가 걸린다고 해보자.
그리고 플레이어가 오른쪽 방향키를 2번 연속 눌러, 오른쪽으로 2칸 이동하려 한다 해보자.</p>

<p>지금까지의 테크닉을 사용한다면, 이런 일이 발생할 것이다:</p>

<figure style="background-color:#777777;padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="https://www.gabrielgambetta.com/img/fpm2-04.png" style="background-color:#777777" />
<figcaption aria-hidden="true"><i>예측한 상태와 authoritative<sub>승인된</sub> 상태 간 불일치.</i></figcaption>
</figure>

<p>새로운 게임 상태가 도착한 <strong>t = 250 ms</strong> 시점에, 흥미로운 문제가 발생했다.
클라이언트가 예측한 상태는 <strong>x = 12</strong>인데, 서버는 새로운 게임 상태가 <strong>x = 11</strong>이라고 말한다.
서버가 최종 결정권을 가지므로<sub>authoritative</sub>, 클라이언트는 캐릭터 위치를 <strong>x = 11</strong>로 되돌려야 한다.
그런데 그 후, <strong>t = 350</strong>에 새로운 서버 상태가 도착하고, <strong>x = 12</strong>라고 하므로, 캐릭터가 이번엔 앞으로 워프를 한다.</p>

<p>플레이어의 관점에서 보면, 오른쪽 방향키를 2번 누른 이후, 캐릭터가 오른쪽으로 2칸 이동했고,
거기 50 ms 동안 서 있다가, 갑자기 왼쪽으로 1칸 워프했다가, 100 ms 동안 서 있다가, 오른쪽으로 1칸 워프한다.
당연히 이대로 놔둘 수는 없다.</p>

<h1 id="server-reconciliation">Server reconciliation</h1>

<p>이 문제를 해결하려면, 클라이언트는 게임 월드의 <em>현재 시간</em>을 보지만, 서버에서 도착하는 업데이트는 랙 때문에 <em>과거 시점</em>이라는 점을 이해해야 한다.
서버가 업데이트된 게임 상태를 보내는 시점에는, 클라이언트의 모든 명령을 처리한 게 아니다.</p>

<p>이 문제를 회피하는 게 그리 어려운 건 아니다.
우선, 클라이언트는 각 요청에 sequence number<sub>시퀀스 번호</sub>를 추가한다.
우리 예시에서는, 첫번째 키 입력은 요청 #1, 두번째 키 입력은 요청 #2 이다.
그 다음, 서버가 응답을 할 때, 마지막으로 처리한 입력의 sequence number를 포함해 보낸다:</p>

<figure style="background-color:#777777;padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="https://www.gabrielgambetta.com/img/fpm2-05.png" style="background-color:#777777" />
<figcaption aria-hidden="true"><i>클라이언트 측 예측 + server reconciliation<sub>서버 조율</sub>.</i></figcaption>
</figure>

<p>이제, <strong>t = 250</strong> 시점에, 서버가 <strong>“네 요청 #1 까지 본 결과, 네 위치는 x = 11”</strong>이라고 말한 것이 된다.
서버가 권위적이므로<sub>authoritative</sub>, 캐릭터 위치는 <strong>x = 11</strong>로 설정된다.
이번엔 클라이언트가 서버로 보낸 각 요청을 저장해둔다고 하자.
새로 도착한 게임 상태를 보면, 서버가 이미 요청 #1 을 처리했다는 걸 알 수 있으므로, 그 요청은 이제 버려도 된다.
하지만 아직 요청 #2 에 대한 결과는 서버로부터 오지 않았다는 것도 알 수 있다.
그러므로 클라이언트 측 예측을 다시 적용하여, 클라이언트는 서버가 보낸 마지막 authoritative 상태에서부터, 서버에서 아직 처리되지 않은 입력을 더하여 “현재” 상태를 추정할 수 있다.</p>

<p><strong>t = 250</strong> 시점에, 클라이언트는 <strong>“네 요청 #1 까지 본 결과, 네 위치는 x = 11”</strong> 메시지를 받는다.
클라이언트는 #1 까지의 전송했던 입력을 버리지만, 아직 서버에서 승인<sub>acknowledge</sub>받지 않은 #2 는 유지한다.
클라이언트는 내부 게임 상태를 서버가 보낸 <strong>x = 11</strong>까지 업데이트하고, 아직 서버에서 확인하지 않은 모든 입력을 적용한다.
이 경우, 입력 #2, <strong>“오른쪽으로 1칸 이동”</strong>을 적용한다.
결과는 <strong>x = 12</strong>이고, 올바르다.</p>

<p>예제를 계속하면, <strong>t = 350</strong> 시점에 서버로부터 <strong>“x = 12, 마지막으로 처리된 요청 = #2”</strong> 메시지가 도착한다.
이 시점에, 클라이언트는 #2 까지의 입력을 모두 버리고, 상태를 <strong>x = 12</strong>로 업데이트한다.
더 이상 다시 실행할<sub>replay</sub> 미처리 입력이 없으므로, 처리는 거기서 끝나고, 결과는 올바르다.</p>

<h1 id="odds-and-ends">Odds and ends</h1>

<p>위에서 다룬 예제는 이동 처리를 다루지만, 같은 원리를 거의 모든 것에 적용할 수 있다.
예를 들어, 턴제 대전 게임에서, 플레이어가 다른 캐릭터를 공격할 때,
유혈이나 데미지 수치를 보여줄 수 있지만, 서버가 대답하기 전까지는 실제 캐릭터의 체력을 업데이트 해서는 안 된다.</p>

<p>쉽게 되돌릴 수 없는 복잡한 게임 상태의 경우, HP가 0이라고 하더라도 서버에서 결과가 올 때까지 캐릭터를 죽이는 것을 피해야 할 수도 있다.
(만일 상대 캐릭터가 죽기 직전 구급상자를 사용했는데, 서버가 아직 그걸 알려주지 않았다면 어쩔 것인가?)</p>

<p>이건 흥미로운 점이다.
월드가 완벽히 결정론적이고 치터가 전혀 없어도, 클라이언트가 예측한 상태와 서버에서 도착한 상태가 reconciliation<sub>조율</sub> 이후엔 맞지 않을 수 있다.
싱글 플레이어에서는 불가능한 시나리오이지만, 서버에 여러 명의 플레이어가 있는 상황에서는 흔히 나타날 수 있는 상황이다.
다음 글에서는 이에 대해 다루겠다.</p>

<h2 id="summary">Summary</h2>

<p>Authoritative server를 사용할 때, 플레이어에겐 반응성이라는 환상<sub>illusion of responsiveness</sub>을 보여 주되, 서버에서 실제로 입력이 처리되기를 기다려야 한다.
그러기 위해, 클라이언트는 입력의 결과를 시뮬레이션<sub>simulates</sub>한다.
업데이트된 서버 상태가 도착하면, 예측했던 클라이언트 상태는 업데이트된 상태와 전송했으나 아직 서버가 승인<sub>acknowledge</sub>하지 않은 입력으로부터 재계산된다<sub>recomputed</sub>.</p>

<p><a href="/2025/04/05/fast-paced-multiplayer-1">« Part I: Client-Server Game Architecture</a> · <strong><a href="/2025/04/05/fast-paced-multiplayer-3">Part III: Entity Interpolation »</a></strong></p>

<p><em>마지막 수정 : 2025-04-06 09:12:00 +0900</em></p>]]></content><author><name>Gabriel Gambetta</name></author><category term="Netcode" /><summary type="html"><![CDATA[본 포스트는 Gabriel Gambetta의 Fast-Paced Multiplayer (Part II): Client-Side Prediction and Server Reconciliation를 한국어로 번역한 것입니다. This post is a Korean translation of the Fast-Paced Multiplayer (Part II): Client-Side Prediction and Server Reconciliation by Gabriel Gambetta.]]></summary></entry><entry><title type="html">Fast-Paced Multiplayer (Part III) - Entity Interpolation</title><link href="https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-3.html" rel="alternate" type="text/html" title="Fast-Paced Multiplayer (Part III) - Entity Interpolation" /><published>2025-04-05T00:00:00+00:00</published><updated>2025-04-06T00:12:00+00:00</updated><id>https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-3</id><content type="html" xml:base="https://copyrat90.github.io/2025/04/05/fast-paced-multiplayer-3.html"><![CDATA[<p>본 포스트는 <a href="https://www.gabrielgambetta.com/entity-interpolation.html">Gabriel Gambetta의 <em>Fast-Paced Multiplayer (Part III): Entity Interpolation</em></a>를 한국어로 번역한 것입니다.<br />
This post is a Korean translation of the <a href="https://www.gabrielgambetta.com/entity-interpolation.html"><em>Fast-Paced Multiplayer (Part III): Entity Interpolation</em> by Gabriel Gambetta</a>.</p>

<p>시리즈의 다른 글 링크:</p>
<ol>
  <li><a href="/2025/04/05/fast-paced-multiplayer-1">Client-Server Game Architecture</a></li>
  <li><a href="/2025/04/05/fast-paced-multiplayer-2">Client-Side Prediction and Server Reconciliation</a></li>
  <li>Entity Interpolation (현재 글)</li>
  <li><a href="/2025/04/06/fast-paced-multiplayer-4">Lag Compensation</a></li>
  <li><a href="https://www.gabrielgambetta.com/client-side-prediction-live-demo.html">Live Demo</a></li>
</ol>

<h1 id="introduction">Introduction</h1>

<p>시리즈의 <a href="/2025/04/05/fast-paced-multiplayer-1">첫번째 글</a>에서, <em>authoritative server</em>와 그것이 클라이언트 치트를 막는데 효과적임을 소개했다.
그러나, 이 테크닉을 순진하게<sub>naively</sub> 적용하면 플레이 가능성<sub>playability</sub>과 반응성<sub>responsiveness</sub>을 가로막는 잠재적 방해 요인<sub>showstopper</sub>이 될 수 있다.
<a href="/2025/04/05/fast-paced-multiplayer-2">두번째 글</a>에서는, 이런 한계를 극복하는 방법으로 <em>클라이언트 측 예측<sub>client-side prediction</sub></em>을 제안했다.</p>

<p>두 글의 내용<sub>net result</sub>은 전송 지연이 있는 authoritative server와 연결되어도, 플레이어가 게임 내 캐릭터를 싱글 플레이어와 똑같은 느낌으로 조작할 수 있게 하는 개념과 테크닉이었다.</p>

<p>이 글에서는, 다른 플레이어가 조작하는 캐릭터가 동일한 서버에 연결된 경우 나타날 수 있는 일에 대해 다룬다.</p>

<h1 id="server-time-step">Server time step</h1>

<p>이전 글에서, 우리가 묘사한 서버의 동작은 꽤 단순했다.
클라이언트의 입력을 읽고, 게임 상태를 업데이트 한 후, 클라이언트에게 되돌려주는 것이었다.
그러나, 1명 이상의 클라이언트가 연결되는 경우, 메인 서버 루프는 다소 달라지게 된다.</p>

<p>그런 경우, 여러 클라이언트가 빠른 주기로 동시에 입력을 보낼 수 있다.
(플레이어가 방향키를 누르든, 마우스를 움직이든, 클릭을 하든 명령을 생성하는 주기로 보낼 것이다.)
매번 입력을 받을 때마다 게임 월드를 업데이트하고 게임 상태를 전파<sub>broadcast</sub>하는 것은 너무 많은 CPU 시간과 대역폭<sub>bandwidth</sub>을 낭비할 것이다.</p>

<p>더 나은 방법론은 클라이언트의 입력을 받을 때, 어떤 처리도 하지 않고 대기열에 넣는<sub>queue</sub> 것이다.
그 대신, 게임 월드는 예를 들어 1초에 10번 정도의 낮은 주기로 업데이트된다.
매 업데이트 사이의 지연을 (이 경우 100 ms) 일컬어 time step<sub>단위 시간</sub>이라 한다.
매 업데이트 루프 반복마다, 처리되지 않은 클라이언트 입력 전체가 적용되고 (물리를 더 예측 가능하게 만들기 위해, time step보다 작은 단위의 시간 증가값으로 처리될 수 있다), 새로운 게임 상태가 클라이언트들에게 전파된다.</p>

<p>요약하면, 게임 월드는 클라이언트 입력 여부와 그 양에 관계 없이, 예측 가능한 빈도<sub>predictable rate</sub>로 업데이트된다.</p>

<h1 id="dealing-with-low-frequency-updates">Dealing with low-frequency updates</h1>

<p>클라이언트의 관점에서, 이 방식은 기존과 같이 부드럽게<sub>smoothly</sub> 동작한다.
클라이언트 측 예측은 업데이트 지연과 독립적으로 작동하므로, 예측 가능하지만 다소 드문 빈도<sub>relatively infrequent</sub>의 상태 업데이트에 대해서도 잘 동작할 것이다.
그러나, 게임 상태가 낮은 빈도로 전파되므로 (기존 예시를 계속하면, 매 100 ms 마다), 클라이언트는 월드를 돌아다니는 다른 개체들<sub>entities</sub>에 대해 너무 듬성듬성<sub>sparse</sub>한 정보만을 얻게 된다.</p>

<p>첫번째 구현은 상태 업데이트를 받을 때에 다른 캐릭터의 위치를 업데이트하는 것이다.
이는 곧바로 뚝뚝 끊어지는<sub>choppy</sub> 움직임을 야기하는데, 그 말은, 부드럽게 움직이는 대신 100 ms 마다 띄엄띄엄<sub>discrete</sub> 점프를 한다는 의미다.</p>

<figure style="background-color:#777777;padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="https://www.gabrielgambetta.com/img/fpm3-01.png" style="background-color:#777777" />
<figcaption aria-hidden="true"><i>클라이언트 2가 바라본 클라이언트 1.</i></figcaption>
</figure>

<p>이 문제에 대한 대응책은 개발하고 있는 게임의 종류에 따라 여러 가지로 나뉜다.
일반적으로는, 게임 개체들<sub>entities</sub>이 예측 가능할수록, 올바르게 처리하기 쉽다.</p>

<h1 id="dead-reckoning">Dead reckoning</h1>

<p>자동차 레이싱 게임을 만들고 있다고 해보자.
아주 빠르게 달리는 자동차의 움직임은 꽤 예측이 쉽다.
예를 들어, 차가 1초에 100m 를 움직인다면, 1초 뒤 시작 지점부터 대략 100m 앞에 있을 것으로 예측할 수 있다.</p>

<p>왜 “대략”인가?
그 1초 사이에 자동차가 약간 가속하거나 감속했을 수 있고, 좌측이나 우측으로 약간 회전했을 수 있다.
여기서의 핵심 단어는 “약간”이다.
고속에서는 자동차의 기동성<sub>maneuverability</sub> 때문에, 플레이어의 실제 행동을 고려하더라도, 특정 시점의 위치는 직전 위치, 속력 및 방향에 상당히 의존적이다.
다른 말로 하면, 레이싱 카는 한 순간에 180° 회전을 할 수 없다.</p>

<p>이 사실을 100 ms 마다 업데이트를 보내는 서버와의 통신에서 어떻게 이용할 수 있을까?
클라이언트는 각 상대 차량에 대한 승인된<sub>authoritative</sub> 속력과 방향<sub>heading</sub> 정보를 받는다.
다음 100 ms 동안은 새로운 정보를 받을 수 없지만, 여전히 화면에는 다른 차들이 달리는 모습을 보여줘야 한다.
가장 간단한 방법은 차의 방향과 가속이 그 100 ms 동안 일정할 것이라 가정하고, 그 차의 물리를 로컬에서 연산하는 것이다.
그 후, 100 ms 가 지나 서버의 업데이트가 도착하면, 차의 위치가 조정된다<sub>corrected</sub>.</p>

<p>이 조정<sub>correction</sub>은 여러 요인에 따라 클 수도 작을 수도 있다.
만약 플레이어가 실제로 차를 일직선상에서 속력 변화 없이 몰았다면, 예측된 위치는 조정할 위치와 정확히 같을 것이다.
반면에, 플레이어가 뭔가와 부딪혔다면, 예측한 위치는 완전히 틀렸을 것이다.</p>

<p>Dead reckoning<sub>추측 항법</sub>은 전함과 같은 느린 속력의 상황에서도 쓸 수 있다는 점에 주목하라.
사실, “dead reckoning<sub>추측 항법</sub>“이라는 용어 자체가 해양 항해<sub>marine navigation</sub>에서 온 말이다.</p>

<h1 id="entity-interpolation">Entity interpolation</h1>

<p>상황에 따라 dead reckoning을 전혀 적용할 수 없을 수도 있다.
특히, 플레이어의 방향과 속력이 즉각적으로 바뀔 수 있는 모든 상황에서 그러하다.
예를 들어, 3D 슈팅 게임에서, 플레이어들은 아주 빠른 속도로 달리고, 멈추고, 직각으로 꺾는데<sub>turn corners</sub>,
이는 dead reckoning을 본질적으로 쓸모 없게 만든다.
새로운 위치와 속력이 이전 데이터로부터 예측될 수 없기 때문이다.</p>

<p>서버가 승인된<sub>authoritative</sub> 데이터를 보낼 때에만 플레이어 위치를 업데이트 할 수는 없다.
그렇게 되면 플레이어들이 100 ms 마다 짧은 거리를 순간이동하게 되고, 그래서는 게임을 플레이 할 수가 없다.</p>

<p>우리가 가진 것은 매 100 ms 마다 받는 승인된<sub>authoritative</sub> 위치 데이터이다.
비결<sub>trick</sub>은 플레이어에게 그 중간에 일어나는 일을 어떻게 보여주느냐다.
해결책의 핵심은 유저의 플레이어의 비해 다른 플레이어들은 <em>과거의 모습으로</em> 보여주는 것이다.</p>

<p><strong>t = 1000</strong>에 위치 정보를 받았다고 해보자.
이미 <strong>t = 900</strong>에 위치 정보를 받았으므로, 다른 플레이어가 <strong>t = 900</strong>과 <strong>t = 1000</strong>에 어디에 있었는지는 알고 있다.
그러므로, <strong>t = 1000</strong>에서 <strong>t = 1100</strong> 동안, 다른 플레이어가 <strong>t = 900</strong>에서 <strong>t = 1000</strong> 사이에 한 일을 보여주면 된다.
이 방법대로면 항상 유저에게 <em>실제 움직임 데이터</em>를 보여줄 수 있다.
다만 이를 100 ms “늦게” 보여줄 뿐이다.</p>

<figure style="background-color:#777777;padding:1em;border-radius:1em;display:table;text-align:center;margin:auto">
<img src="https://www.gabrielgambetta.com/img/fpm3-02.png" style="background-color:#777777" />
<figcaption aria-hidden="true"><i>클라이언트 2는 클라이언트 1의 알려진 위치 사이를 보간하여, "과거를 렌더링"한다.</i></figcaption>
</figure>

<p><strong>t = 900</strong>에서 <strong>t = 1000</strong> 사이를 보간<sub>interpolate</sub>하기 위해 사용하는 위치 데이터는 게임에 따라 달라진다.
보통은 보간<sub>interpolation</sub>이면 충분하다.
그렇지 못한 경우, 서버에서 매 업데이트마다 더 디테일한 이동 데이터를 보내도록 할 수 있다.
예를 들어, 플레이어 정보 뒤에 직진한 구간의 목록<sub>sequence of straight segments</sub>을 붙여 보내거나, 10 ms 마다 샘플링한 위치 정보를 보내 보간을 더 보기 좋게 만들 수도 있다.
(10배나 더 많은 데이터를 보낼 필요는 없다. 작은 움직임의 변화값들<sub>deltas</sub>만을 보내는 것이므로, 통신에 사용할 포맷<sub>format on the wire</sub>은 이를 고려해 특수한 최적화를 하면 된다.)</p>

<p>이 테크닉을 사용하겠다면, 모든 플레이어가 서로 약간 다른 게임 월드를 보게 된다는 점을 기억해야 한다.
왜냐하면 각 플레이어는 자기 자신은 <em>현재 모습</em>을 보지만, 다른 개체들<sub>entities</sub>은 <em>과거 모습</em>으로 보기 때문이다.
그러나, 호흡이 빠른 게임이라 할 지라도, 다른 개체들이 100 ms 지연되어 보이는 정도는 알아채기 어렵다.</p>

<p>예외는 있다.
플레이어가 다른 플레이어를 사격하는 등 시간, 공간적으로 정밀해야 하는 경우이다.
다른 플레이어는 과거의 모습으로 보고 있으므로, 100 ms 의 지연 시간을 갖고 조준하고 있는 것이다.
다시 말해, 목표물의 100 ms 이전 위치에 대고 사격하고 있는 것이다!
이걸 처리하는 법은 다음 글에서 다루도록 하자.</p>

<h1 id="summary">Summary</h1>

<p>드문 빈도<sub>infrequent</sub>의 업데이트와 네트워크 지연이 있는 Authoritative server를 사용하는 클라이언트-서버 환경에서도, 여전히 플레이어에게 연속성의 환상<sub>illusion of continuity</sub>과 부드러운 움직임을 제공해야 한다.
<a href="/2025/04/05/fast-paced-multiplayer-2">시리즈의 2편</a>에서 유저가 조작하는 플레이어의 이동을 실시간으로 보여 주기 위해, 클라이언트 측 예측과 서버 조율<sub>server reconciliation</sub>을 활용하였다.
이는 사용자 입력이 로컬 플레이어에게 즉시 적용되도록 하여, 게임플레이를 불가능하게 만드는 렌더링 지연을 제거했다.</p>

<p>그러나, 다른 개체들은 여전히 문제였다.
이번 글에서 이를 해결하기 위한 2가지 다른 방법을 살펴보았다.</p>

<p>첫번째 방법은, dead reckoning<sub>추측 항법</sub>으로, 위치, 속도와 가속 등 이전 데이터로부터 개체의 현재 위치를 잘 추정할 수 있는 종류의 시뮬레이션에 적용할 수 있는 방법론이다.
이 방법론은 추측이 어려운 상황에서는 쓸 수 없다.</p>

<p>두번째 방법은, entity interpolation<sub>개체 보간</sub>으로, 미래를 전혀 예측하지 않는다.
오로지 서버로부터 받은 실제 개체 데이터만을 사용하므로, 다른 개체들이 살짝 지연되어 보이게 된다.</p>

<p>결론적인 효과<sub>net effect</sub>는 유저의 플레이어는 <em>현재 모습</em>으로 보이지만, 다른 개체들은 <em>과거 모습</em>으로 보인다는 것이다.
이는 보통은 아주 매끄러운<sub>seamless</sub> 경험을 선사한다.</p>

<p>그러나, 다른 방책이 없으면, 이동하는 목표물을 사격하는 등 시공간적으로 정밀해야 하는 경우 이런 환상은 무너지게 된다.
클라이언트 2에서 렌더링하는 클라이언트 1의 위치는, 서버에서의 위치와도, 클라이언트 1에서의 위치와도 맞지 않으며, 헤드샷을 불가능하게 만든다!
헤드샷이 없으면 성립하는 게임은 없으므로, 다음 글에서 이 문제를 다뤄보도록 하겠다.</p>

<p><a href="/2025/04/05/fast-paced-multiplayer-2">« Part II: Client-Side Prediction and Server Reconciliation</a> · <strong><a href="/2025/04/06/fast-paced-multiplayer-4">Part IV: Lag Compensation »</a></strong></p>

<p><em>마지막 수정 : 2025-04-06 09:12:00 +0900</em></p>]]></content><author><name>Gabriel Gambetta</name></author><category term="Netcode" /><summary type="html"><![CDATA[본 포스트는 Gabriel Gambetta의 Fast-Paced Multiplayer (Part III): Entity Interpolation를 한국어로 번역한 것입니다. This post is a Korean translation of the Fast-Paced Multiplayer (Part III): Entity Interpolation by Gabriel Gambetta.]]></summary></entry><entry><title type="html">(C#) async-await 패턴에 사용할 custom awaitable 작성하기</title><link href="https://copyrat90.github.io/2025/03/23/csharp-custom-awaitable.html" rel="alternate" type="text/html" title="(C#) async-await 패턴에 사용할 custom awaitable 작성하기" /><published>2025-03-23T00:00:00+00:00</published><updated>2025-05-03T05:38:00+00:00</updated><id>https://copyrat90.github.io/2025/03/23/csharp-custom-awaitable</id><content type="html" xml:base="https://copyrat90.github.io/2025/03/23/csharp-custom-awaitable.html"><![CDATA[<p>C# 에서 async-await 패턴의 작동 방식과, 그를 이용한 custom awaitable 작성하기.</p>

<h1 id="배경">배경</h1>

<p>최근 2주간 <a href="https://github.com/ValveSoftware/GameNetworkingSockets">GameNetworkingSockets</a>를 <a href="https://github.com/nalchi-net/GnsSharp">C#에서 P/Invoke로 감싸는 나만의 라이브러리 GnsSharp</a>을 직접 바닥부터 만들었다.</p>

<p>더 나아가서 아예 Steamworks API 전용 기능 일부까지 binding하고 있었는데, 그중 비동기 <a href="https://partner.steamgames.com/doc/sdk/api#callresults">Steam CallResults</a>를 C# 스타일에 맞게 async-await으로 만들어야겠다고 생각해서, 한번 조사해봤다.</p>

<h1 id="async-await의-동작-방식">async-await의 동작 방식</h1>

<p>기본 개념은 아래 이미지 한 장이면 다 설명이 된다. <a href="https://vkontech.com/exploring-the-async-await-state-machine-the-awaitable-pattern/">(출처)</a></p>

<p><img src="https://i0.wp.com/vkontech.com/wp-content/uploads/2020/11/image.png" alt="" /></p>

<p>좀 더 구체적으로 코드상으로 어떻게 표현되는지 보자.</p>

<p>C# 에서는 <code class="language-plaintext highlighter-rouge">GetAwaiter()</code> method를 갖는 클래스는 자동으로 awaitable이 된다. (duck typing?)<br />
이 때, 반환되는 awaiter는 다음 조건들을 만족시켜야 한다.</p>
<ul>
  <li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.inotifycompletion?view=net-9.0"><code class="language-plaintext highlighter-rouge">INotifyCompletion</code></a> 또는 <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.icriticalnotifycompletion?redirectedfrom=MSDN&amp;view=net-9.0"><code class="language-plaintext highlighter-rouge">ICriticalNotifyCompletion</code></a> 상속.
    <ul>
      <li>이 말은, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.inotifycompletion.oncompleted?view=net-9.0#system-runtime-compilerservices-inotifycompletion-oncompleted(system-action)"><code class="language-plaintext highlighter-rouge">INotifyCompletion.OnCompleted(Action)</code></a>을 구현해야 한다는 말이다.</li>
      <li>후자를 상속받은 경우, 추가로 <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.icriticalnotifycompletion.unsafeoncompleted?view=net-9.0#system-runtime-compilerservices-icriticalnotifycompletion-unsafeoncompleted(system-action)"><code class="language-plaintext highlighter-rouge">ICriticalNotifyCompletion.UnsafeOnCompleted(Action)</code></a>도 구현해야 한다.</li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">bool IsCompleted { get; }</code> property를 갖고 있어야 한다.</li>
  <li><code class="language-plaintext highlighter-rouge">GetResult()</code> method를 갖고 있어야 한다.
    <ul>
      <li>이 녀석의 반환형이 <code class="language-plaintext highlighter-rouge">await</code>시에 반환되는 type이 된다.</li>
    </ul>
  </li>
</ul>

<p><code class="language-plaintext highlighter-rouge">var outcome = await task;</code>를 했을 때, 위 멤버들이 실제 작동하는 방식은 아래와 비슷하다. <a href="https://www.jacksondunstan.com/articles/4918">(출처)</a></p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">awaiter</span> <span class="p">=</span> <span class="n">task</span><span class="p">.</span><span class="nf">GetAwaiter</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="n">awaiter</span><span class="p">.</span><span class="n">IsCompleted</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// Remove 'outcome =' if `GetResult` returns void</span>
    <span class="n">outcome</span> <span class="p">=</span> <span class="n">awaiter</span><span class="p">.</span><span class="nf">GetResult</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">else</span>
<span class="p">{</span>
    <span class="nf">SuspendTheFunction</span><span class="p">();</span>

    <span class="n">Action</span> <span class="n">continuation</span> <span class="p">=</span> <span class="p">()</span> <span class="p">=&gt;</span> <span class="p">{</span>
        <span class="nf">ResumeTheFunction</span><span class="p">();</span>
        <span class="c1">// Remove 'outcome =' if `GetResult` returns void</span>
        <span class="n">outcome</span> <span class="p">=</span> <span class="n">awaiter</span><span class="p">.</span><span class="nf">GetResult</span><span class="p">();</span>
    <span class="p">};</span>
    <span class="kt">var</span> <span class="n">cnc</span> <span class="p">=</span> <span class="n">awaiter</span> <span class="k">as</span> <span class="n">ICriticalNotifyCompletion</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">cnc</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">cnc</span><span class="p">.</span><span class="nf">UnsafeOnCompleted</span><span class="p">(</span><span class="n">continuation</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">else</span>
    <span class="p">{</span>
        <span class="n">awaiter</span><span class="p">.</span><span class="nf">OnCompleted</span><span class="p">(</span><span class="n">continuation</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>즉, 우선 <code class="language-plaintext highlighter-rouge">GetAwaiter()</code>로 awaiter를 가져오고:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">awaiter.IsCompleted</code>가 <code class="language-plaintext highlighter-rouge">true</code>이면 이미 비동기 처리가 완료된 것이므로 <code class="language-plaintext highlighter-rouge">awaiter.GetResult()</code>로 즉시 결과를 가져온다.
    <ul>
      <li>이 경우, method의 중단 없이 현재 thread가 계속 후속 method 코드를 실행할 것이다.</li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">awaiter.IsCompleted</code>가 <code class="language-plaintext highlighter-rouge">false</code>이면 아직 비동기 처리가 완료되지 않은 것이므로:
    <ol>
      <li>현재 실행중인 method를 중단시킨다.</li>
      <li>중단점으로부터 method를 재시작하는 <code class="language-plaintext highlighter-rouge">ResumeTheFunction()</code>이라는 특수한 함수를 만들고, 그걸 호출 후 결과를 받아오는 <code class="language-plaintext highlighter-rouge">awaiter.GetResult()</code>를 그 이후에 호출하도록 하는 <code class="language-plaintext highlighter-rouge">continuation</code> Action을 하나 만든다.</li>
      <li>awaiter의 타입에 따라 <code class="language-plaintext highlighter-rouge">OnCompleted()</code>나 <code class="language-plaintext highlighter-rouge">UnsafeOnCompleted()</code>에 <code class="language-plaintext highlighter-rouge">continuation</code>을 매개변수로 넘겨서 method의 재개를 등록하게 한다.
        <ul>
          <li>이 경우, 현재 thread와 후속 method 코드를 재개하는 thread가 다를 수도 있다.<br />
물론 같을 수도 있다. 그건 <code class="language-plaintext highlighter-rouge">continuation</code>을 누가 Invoke하는 지에 따라 결정될 것.</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

<p>위 동작을 나타낸 이미지 <a href="https://vkontech.com/exploring-the-async-await-state-machine-the-awaitable-pattern/">(출처)</a></p>

<p><img src="https://i0.wp.com/vkontech.com/wp-content/uploads/2020/11/image-1.png" alt="" /></p>

<h2 id="예시-1-task와-taskawaiter">예시 1. <code class="language-plaintext highlighter-rouge">Task</code>와 <code class="language-plaintext highlighter-rouge">TaskAwaiter</code></h2>

<p>흔히 자주 쓰이는 <code class="language-plaintext highlighter-rouge">System.Threading.Tasks</code>의 <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1?view=net-9.0"><code class="language-plaintext highlighter-rouge">Task</code></a>라고 특별한 건 아니고, 위 패턴을 따라 구현되어 있다.<br />
<a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.getawaiter?view=net-9.0"><code class="language-plaintext highlighter-rouge">Task.GetAwaiter()</code></a>는 <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.taskawaiter?view=net-9.0"><code class="language-plaintext highlighter-rouge">TaskAwaiter</code></a>를 반환하며, 이는 위 awaiter의 조건들을 만족한다.</p>

<p>작업이 완료되면, C# 런타임의 <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.threadpool?view=net-9.0"><code class="language-plaintext highlighter-rouge">ThreadPool</code></a> 내의 thread가 <code class="language-plaintext highlighter-rouge">continuation</code>을 호출해 후속 method 코드를 재개한다.<br />
(정확히는, <code class="language-plaintext highlighter-rouge">SynchronizationContext.Current</code>가 기본값 <code class="language-plaintext highlighter-rouge">null</code>인 경우.)<br />
(참고로, Windows에서 장치 I/O를 대기하는 경우에 한정해 <a href="https://blog.stephencleary.com/2013/11/there-is-no-thread.html">기존에는 IOCP worker thread가 관여했는데</a>, .NET 7부터는 <a href="https://github.com/dotnet/runtime/issues/46610#issuecomment-1109014759">managed thread pool에서 batch polling을 통해 처리한다고 한다.</a>)</p>

<h2 id="예시-2-godotsharp의-signalawaiter">예시 2. GodotSharp의 <code class="language-plaintext highlighter-rouge">SignalAwaiter</code></h2>

<p>Godot Engine에서 <a href="https://github.com/godotengine/godot/blob/2303ce843a362cf5497ca3336451de23793eb711/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotObject.base.cs#L192-L195"><code class="language-plaintext highlighter-rouge">GodotObject.ToSignal()</code></a> method를 호출하면 <a href="https://github.com/godotengine/godot/blob/2303ce843a362cf5497ca3336451de23793eb711/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalAwaiter.cs"><code class="language-plaintext highlighter-rouge">SignalAwaiter</code></a>가 반환되는데, 이 녀석은 awaitable과 awaiter의 역할을 동시에 수행한다.</p>

<p>Signal을 보내면, C++ 엔진 수준에서 <a href="https://github.com/godotengine/godot/blob/2303ce843a362cf5497ca3336451de23793eb711/modules/mono/glue/GodotSharp/GodotSharp/Core/SignalAwaiter.cs#L33-L65"><code class="language-plaintext highlighter-rouge">SignalAwaiter.SignalCallback()</code></a>을 호출해 <code class="language-plaintext highlighter-rouge">continuation</code>을 수행하는 것으로 보인다.<br />
기본적으로 게임 루프를 돌리는 main thread가 Signal emission도 담당하는 것으로 보이므로, main thread에서 <code class="language-plaintext highlighter-rouge">await ToSignal()</code>을 했었다면 후속 처리도 같은 thread일 것이다.</p>

<h1 id="내-라이브러리에서의-custom-awaitable-구현-calltaskt">내 라이브러리에서의 custom awaitable 구현: <code class="language-plaintext highlighter-rouge">CallTask&lt;T&gt;</code></h1>

<p>내가 만든 <a href="https://github.com/nalchi-net/GnsSharp">GnsSharp</a>에서는 <a href="https://github.com/nalchi-net/GnsSharp/blob/main/GnsSharp/CallTask.cs"><code class="language-plaintext highlighter-rouge">CallTask&lt;T&gt;</code></a>가 awaitable과 awaiter의 역할을 동시에 수행한다.</p>

<p>Steamworks API 구현 스타일과 동일하게 <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/SteamAPI.cs#L206-L213"><code class="language-plaintext highlighter-rouge">SteamAPI.RunCallbacks()</code></a>를 제공하고, 이걸 유저가 직접 호출해야 한다.<br />
그러면 <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/Dispatcher.cs#L17-L97"><code class="language-plaintext highlighter-rouge">Dispatcher.RunCallbacks()</code></a> -&gt; <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/ISteamUtils.cs#L778-L846"><code class="language-plaintext highlighter-rouge">ISteamUtils.OnDispatch()</code></a> -&gt; <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/ISteamUtils.cs#L848-L870"><code class="language-plaintext highlighter-rouge">ISteamUtils.HandleCallCompletedResult()</code></a>를 거쳐서 최종적으로 <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/CallTask.cs#L76-L111"><code class="language-plaintext highlighter-rouge">CallTask&lt;T&gt;.SetResultFrom()</code></a>이 호출된다.</p>

<p>유저가 <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/SteamAPI.cs#L206-L213"><code class="language-plaintext highlighter-rouge">SteamAPI.RunCallbacks()</code></a>를 별도의 thread에서 돌릴 수도 있으므로, 내부에 <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/CallTask.cs#L17"><code class="language-plaintext highlighter-rouge">taskLock</code></a>을 하나 둬서 동기화 문제를 방지한다.</p>

<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">void</span> <span class="nf">OnCompleted</span><span class="p">(</span><span class="n">Action</span> <span class="n">continuation</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">bool</span> <span class="n">lockTaken</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
    <span class="k">try</span>
    <span class="p">{</span>
        <span class="n">Monitor</span><span class="p">.</span><span class="nf">Enter</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">taskLock</span><span class="p">,</span> <span class="k">ref</span> <span class="n">lockTaken</span><span class="p">);</span>

        <span class="c1">// 혹시 `taskLock` 걸기 전에 결과를 받은 게 아닌지 double-check</span>
        <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">IsCompleted</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c1">// 결과가 왔으면, `taskLock`을 해제하고...</span>
            <span class="n">Monitor</span><span class="p">.</span><span class="nf">Exit</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">taskLock</span><span class="p">);</span>
            <span class="n">lockTaken</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>

            <span class="c1">// ...`continuation`을 호출해 즉시 재개</span>
            <span class="nf">continuation</span><span class="p">();</span>
        <span class="p">}</span>
        <span class="k">else</span>
        <span class="p">{</span>
            <span class="c1">// 결과가 없었으면, 차후에 `RunCallbacks()` 돌리는 thread가 호출하도록</span>
            <span class="c1">// `continuation`을 내부에 저장해 둠</span>
            <span class="k">this</span><span class="p">.</span><span class="n">continuation</span> <span class="p">=</span> <span class="n">continuation</span><span class="p">;</span>

            <span class="c1">// `continuation`을 재개할 현재 thread의 SynchronizationContext를 저장해 둠</span>
            <span class="k">this</span><span class="p">.</span><span class="n">syncContext</span> <span class="p">=</span> <span class="n">SynchronizationContext</span><span class="p">.</span><span class="n">Current</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
    <span class="k">finally</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">lockTaken</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">Monitor</span><span class="p">.</span><span class="nf">Exit</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">taskLock</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">OnCompleted()</code>가 호출됐는데 (즉 <code class="language-plaintext highlighter-rouge">IsCompleted</code>가 <code class="language-plaintext highlighter-rouge">false</code>였는데), <code class="language-plaintext highlighter-rouge">taskLock</code>을 소유하기 전 틈에 또 <code class="language-plaintext highlighter-rouge">SetResultFrom()</code>이 먼저 수행되어 결과를 저장할 수 있으므로,<br />
<code class="language-plaintext highlighter-rouge">taskLock</code>을 소유한 이후 <code class="language-plaintext highlighter-rouge">IsCompleted</code>를 double-check 해서, 결과가 그 틈에 들어왔다면 <code class="language-plaintext highlighter-rouge">continuation()</code>을 호출해 즉시 실행해준다.</p>

<p>결과가 안 들어왔다면 <code class="language-plaintext highlighter-rouge">RunCallbacks()</code>를 돌리는 thread가 호출하도록 <code class="language-plaintext highlighter-rouge">continuation</code>을 내부에 저장해둔다.</p>

<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">void</span> <span class="nf">SetResultFrom</span><span class="p">(</span><span class="n">HSteamPipe</span> <span class="n">pipe</span><span class="p">,</span> <span class="k">ref</span> <span class="n">SteamAPICallCompleted_t</span> <span class="n">callCompleted</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Debug</span><span class="p">.</span><span class="nf">Assert</span><span class="p">(</span><span class="n">T</span><span class="p">.</span><span class="n">CallbackParamId</span> <span class="p">==</span> <span class="n">callCompleted</span><span class="p">.</span><span class="n">AsyncCallbackId</span><span class="p">,</span> <span class="s">$"Callback id mismatch (expected </span><span class="p">{</span><span class="n">T</span><span class="p">.</span><span class="n">CallbackParamId</span><span class="p">}</span><span class="s"> for </span><span class="p">{</span><span class="k">typeof</span><span class="p">(</span><span class="n">T</span><span class="p">)}</span><span class="s">, got </span><span class="p">{</span><span class="n">callCompleted</span><span class="p">.</span><span class="n">AsyncCallbackId</span><span class="p">}</span><span class="s">)"</span><span class="p">);</span>
    <span class="k">unsafe</span>
    <span class="p">{</span>
        <span class="n">Debug</span><span class="p">.</span><span class="nf">Assert</span><span class="p">(</span><span class="k">sizeof</span><span class="p">(</span><span class="n">T</span><span class="p">)</span> <span class="p">==</span> <span class="n">callCompleted</span><span class="p">.</span><span class="n">ParamSize</span><span class="p">,</span> <span class="s">$"Callback param size mismatch (expected </span><span class="p">{</span><span class="k">sizeof</span><span class="p">(</span><span class="n">T</span><span class="p">)}</span><span class="s"> for </span><span class="p">{</span><span class="k">typeof</span><span class="p">(</span><span class="n">T</span><span class="p">)}</span><span class="s">, got </span><span class="p">{</span><span class="n">callCompleted</span><span class="p">.</span><span class="n">ParamSize</span><span class="p">}</span><span class="s">)"</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="kt">bool</span> <span class="n">lockTaken</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>
    <span class="k">try</span>
    <span class="p">{</span>
        <span class="n">Monitor</span><span class="p">.</span><span class="nf">Enter</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">taskLock</span><span class="p">,</span> <span class="k">ref</span> <span class="n">lockTaken</span><span class="p">);</span>

        <span class="c1">// P/Invoke 매개변수로 `this.result`의 Span을 전달하여, Steam CallResult param을 추가적인 복사 없이 바로 받아오기</span>
        <span class="n">Span</span><span class="p">&lt;</span><span class="kt">byte</span><span class="p">&gt;</span> <span class="n">resultRaw</span> <span class="p">=</span> <span class="n">MemoryMarshal</span><span class="p">.</span><span class="nf">AsBytes</span><span class="p">(</span><span class="n">MemoryMarshal</span><span class="p">.</span><span class="nf">CreateSpan</span><span class="p">(</span><span class="k">ref</span> <span class="k">this</span><span class="p">.</span><span class="n">result</span><span class="p">,</span> <span class="m">1</span><span class="p">));</span>
        <span class="kt">bool</span> <span class="n">gotResult</span> <span class="p">=</span> <span class="n">Native</span><span class="p">.</span><span class="nf">SteamAPI_ManualDispatch_GetAPICallResult</span><span class="p">(</span><span class="n">pipe</span><span class="p">,</span> <span class="n">callCompleted</span><span class="p">.</span><span class="n">AsyncCall</span><span class="p">,</span> <span class="n">resultRaw</span><span class="p">,</span> <span class="n">resultRaw</span><span class="p">.</span><span class="n">Length</span><span class="p">,</span> <span class="n">callCompleted</span><span class="p">.</span><span class="n">AsyncCallbackId</span><span class="p">,</span> <span class="k">out</span> <span class="k">this</span><span class="p">.</span><span class="n">isFailed</span><span class="p">);</span>
        <span class="n">Debug</span><span class="p">.</span><span class="nf">Assert</span><span class="p">(</span><span class="n">gotResult</span><span class="p">,</span> <span class="s">"There was no call result available"</span><span class="p">);</span>

        <span class="k">this</span><span class="p">.</span><span class="n">isCompleted</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>

        <span class="c1">// 이미 continuation이 등록된 경우, 재개할 책임은 이쪽에 있다.</span>
        <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">continuation</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">Monitor</span><span class="p">.</span><span class="nf">Exit</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">taskLock</span><span class="p">);</span>
            <span class="n">lockTaken</span> <span class="p">=</span> <span class="k">false</span><span class="p">;</span>

            <span class="c1">// `CallTask`를 await한 thread에 `SynchronizationContext.Current`가 존재했고, `ConfigureAwait(true)` 상태였다면</span>
            <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">continueOnCapturedContext</span> <span class="p">&amp;&amp;</span> <span class="k">this</span><span class="p">.</span><span class="n">syncContext</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="c1">// 해당 synchronization context에 continuation을 재개하도록 예약</span>
                <span class="k">this</span><span class="p">.</span><span class="n">syncContext</span><span class="p">.</span><span class="nf">Post</span><span class="p">(</span><span class="n">cont</span> <span class="p">=&gt;</span> <span class="p">((</span><span class="n">Action</span><span class="p">)</span><span class="n">cont</span><span class="p">!).</span><span class="nf">Invoke</span><span class="p">(),</span> <span class="k">this</span><span class="p">.</span><span class="n">continuation</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">else</span>
            <span class="p">{</span>
                <span class="c1">// 현재 thread에서 바로 continuation 재개</span>
                <span class="k">this</span><span class="p">.</span><span class="nf">continuation</span><span class="p">();</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>
    <span class="k">finally</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">lockTaken</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">Monitor</span><span class="p">.</span><span class="nf">Exit</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">taskLock</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">RunCallbacks()</code>가 결과를 가져와서 <code class="language-plaintext highlighter-rouge">SetResultFrom()</code>으로 저장할 때는, <code class="language-plaintext highlighter-rouge">taskLock</code>을 소유한 상태로 <code class="language-plaintext highlighter-rouge">this.result</code>에 직접 결과를 쓴다.<br />
이 때, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal.asbytes?view=net-9.0"><code class="language-plaintext highlighter-rouge">MemoryMarshal.AsBytes()</code></a>로 <code class="language-plaintext highlighter-rouge">this.result</code>를 <code class="language-plaintext highlighter-rouge">Span&lt;byte&gt;</code> 형식으로 변환하고, 그걸 바로 P/Invoke 함수에 전달하여 불필요한 복사를 최소화한다.<br />
(이게 어떻게 pinning 되어 P/Invoke 호출이 되는지는 <a href="/2025/02/17/nullptr-ref-out-for-interop#설명">이전 글</a>에서 설명한 바 있다.)</p>

<p>만일, 이미 <code class="language-plaintext highlighter-rouge">this.continuation</code>이 등록된 상황이었다면, 재개를 해준다.<br />
이 때, <code class="language-plaintext highlighter-rouge">await</code> 한 측 thread에 <code class="language-plaintext highlighter-rouge">SynchronizationContext.Current</code>가 존재했고, <code class="language-plaintext highlighter-rouge">ConfigureAwait(true)</code> 상태였다면 (기본값),
그 synchronization context에서 재개하도록 예약하고,<br />
존재하지 않았다면, 현재 <code class="language-plaintext highlighter-rouge">SetResultFrom()</code>을 수행 중인 thread에서 바로 재개한다.</p>

<p>반대로, <code class="language-plaintext highlighter-rouge">this.continuation</code>이 등록되지 않았다면 할 일은 없다. <code class="language-plaintext highlighter-rouge">this.isCompleted = true;</code>로 세팅했으므로, <code class="language-plaintext highlighter-rouge">await</code> 한 측에서 재개할 것이다.</p>

<h2 id="사족-steamapicall_t로-calltaskt-찾기">사족: <code class="language-plaintext highlighter-rouge">SteamAPICall_t</code>로 <code class="language-plaintext highlighter-rouge">CallTask&lt;T&gt;</code> 찾기</h2>

<p>Steamworks API 측에서 돌아오는 CallResult 내부에는, 현재 async request의 핸들인 <code class="language-plaintext highlighter-rouge">SteamAPICall_t</code>가 같이 저장되어 들어온다. (그냥 <code class="language-plaintext highlighter-rouge">ulong</code>)<br />
이걸 이용해 <code class="language-plaintext highlighter-rouge">CallTask&lt;T&gt;</code>를 찾아야 하는데, 일단 간단하게 <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/ISteamUtils.cs#L20-L21"><code class="language-plaintext highlighter-rouge">Dictionary&lt;SteamAPICall_t, ICallTask&gt;</code> 1개</a>에다가 모든 <code class="language-plaintext highlighter-rouge">CallTask&lt;T&gt;</code>를 저장해두고 처리하고 있다.</p>

<p>이 때, P/Invoke로 비동기 요청을 보내는 함수가 반환하기도 전에 <code class="language-plaintext highlighter-rouge">RunCallbacks()</code> thread에 호출 결과가 돌아올 가능성도 존재한다.<br />
그러면 <code class="language-plaintext highlighter-rouge">Dictionary</code>에 미처 <code class="language-plaintext highlighter-rouge">(SteamAPICall_t, CallTask&lt;T&gt;)</code>를 집어넣기도 전에 <code class="language-plaintext highlighter-rouge">RunCallbacks()</code> thread에서 찾으려 들어서 못 찾는 상황도 있을 수 있다.<br />
이런 불상사를 방지하기 위해, 아래와 같이 미리 <code class="language-plaintext highlighter-rouge">Dictionary</code>용 <code class="language-plaintext highlighter-rouge">asyncCallTasksLock</code>을 소유한 다음에야 P/Invoke로 비동기 요청을 보내도록 했다.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">internal</span> <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">TResult</span><span class="p">&gt;?</span> <span class="n">SafeSteamAPICall</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">TResult</span><span class="p">&gt;(</span><span class="n">Func</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">SteamAPICall_t</span><span class="p">&gt;</span> <span class="n">nativeCall</span><span class="p">,</span> <span class="n">T1</span> <span class="n">param1</span><span class="p">,</span> <span class="n">T2</span> <span class="n">param2</span><span class="p">)</span>
        <span class="k">where</span> <span class="n">TResult</span> <span class="p">:</span> <span class="n">unmanaged</span><span class="p">,</span> <span class="n">ICallbackParam</span>
        <span class="k">where</span> <span class="n">T1</span> <span class="p">:</span> <span class="n">allows</span> <span class="k">ref</span> <span class="k">struct</span>
        <span class="nc">where</span> <span class="n">T2</span> <span class="p">:</span> <span class="n">allows</span> <span class="k">ref</span> <span class="k">struct</span>
<span class="err">{</span>
    <span class="nc">var</span> <span class="n">task</span> <span class="p">=</span> <span class="k">new</span> <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">TResult</span><span class="p">&gt;();</span>

    <span class="c1">// 우선 Dictionary에 대한 lock을 소유하고...</span>
    <span class="k">lock</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">asyncCallTasksLock</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// ... 그 이후에야 Steam API 비동기 요청을 보냄</span>
        <span class="n">SteamAPICall_t</span> <span class="n">handle</span> <span class="p">=</span> <span class="nf">nativeCall</span><span class="p">(</span><span class="n">param1</span><span class="p">,</span> <span class="n">param2</span><span class="p">);</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">handle</span> <span class="p">==</span> <span class="n">SteamAPICall_t</span><span class="p">.</span><span class="n">Invalid</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="k">null</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="c1">// Dictionary에 (handle, task) 쌍을 저장</span>
        <span class="k">this</span><span class="p">.</span><span class="n">asyncCallTasks</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="n">task</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="n">task</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">private</span> <span class="k">void</span> <span class="nf">HandleCallCompletedResult</span><span class="p">(</span><span class="n">HSteamPipe</span> <span class="n">pipe</span><span class="p">,</span> <span class="k">ref</span> <span class="n">CallbackMsg_t</span> <span class="n">msg</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">ref</span> <span class="kt">var</span> <span class="n">callCompleted</span> <span class="p">=</span> <span class="k">ref</span> <span class="n">msg</span><span class="p">.</span><span class="n">GetCallbackParamAs</span><span class="p">&lt;</span><span class="n">SteamAPICallCompleted_t</span><span class="p">&gt;();</span>

    <span class="n">ICallTask</span><span class="p">?</span> <span class="n">task</span><span class="p">;</span>

    <span class="c1">// Dictionary에 대한 lock을 소유하고...</span>
    <span class="k">lock</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">asyncCallTasksLock</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// ... 해당하는 `ICallTask`를 찾으려고 시도</span>
        <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">asyncCallTasks</span><span class="p">.</span><span class="nf">TryGetValue</span><span class="p">(</span><span class="n">callCompleted</span><span class="p">.</span><span class="n">AsyncCall</span><span class="p">,</span> <span class="k">out</span> <span class="n">task</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="c1">// 찾았으면 Dictionary에서 제거</span>
            <span class="k">this</span><span class="p">.</span><span class="n">asyncCallTasks</span><span class="p">.</span><span class="nf">Remove</span><span class="p">(</span><span class="n">callCompleted</span><span class="p">.</span><span class="n">AsyncCall</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">task</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// 찾았으면 `SetResultFrom()` 호출</span>
        <span class="n">task</span><span class="p">.</span><span class="nf">SetResultFrom</span><span class="p">(</span><span class="n">pipe</span><span class="p">,</span> <span class="k">ref</span> <span class="n">callCompleted</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">else</span>
    <span class="p">{</span>
        <span class="n">Debug</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">$"Got unexpected call result #</span><span class="p">{</span><span class="n">callCompleted</span><span class="p">.</span><span class="n">AsyncCall</span><span class="p">}</span><span class="s">, Id = </span><span class="p">{</span><span class="n">callCompleted</span><span class="p">.</span><span class="n">AsyncCallbackId</span><span class="p">}</span><span class="s">"</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>참고로 유명한 Steamworks 바인딩인 <a href="https://github.com/Facepunch/Facepunch.Steamworks">Facepunch.Steamworks</a>에서는 <a href="https://github.com/Facepunch/Facepunch.Steamworks/blob/aa87fe557fa0578b4361bf0f23848d64d0c94a79/Facepunch.Steamworks/Classes/Dispatch.cs#L265-L277">이 부분을 lock을 안 걸고 처리</a>하는 것으로 보인다.<br />
아니 <code class="language-plaintext highlighter-rouge">RunCallbacks()</code>를 다른 thread에서 돌리면 위험할텐데?</p>

<h3 id="사족의-사족-왜-c엔-variadic-generics가-없는-것인가">사족의 사족: 왜 C#엔 variadic generics가 없는 것인가…</h3>

<p>참고로 위 <code class="language-plaintext highlighter-rouge">SafeSteamAPICall&lt;T1, T2, TResult&gt;()</code>는 그저 매개변수 2개 받는 async Steam API 함수를 호출하는 버전이고,<br />
실제로는 아래와 같이 <a href="https://github.com/nalchi-net/GnsSharp/blob/e2b3db93cc054d880b86d4a813122df9851104c6/GnsSharp/ISteamUtils.cs#L637-L776">6개까지 overload</a>가 되어 있다.</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">internal</span> <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">TResult</span><span class="p">&gt;?</span> <span class="n">SafeSteamAPICall</span><span class="p">&lt;</span><span class="n">T</span><span class="p">,</span> <span class="n">TResult</span><span class="p">&gt;(</span><span class="n">Func</span><span class="p">&lt;</span><span class="n">T</span><span class="p">,</span> <span class="n">SteamAPICall_t</span><span class="p">&gt;</span> <span class="n">nativeCall</span><span class="p">,</span> <span class="n">T</span> <span class="n">param</span><span class="p">);</span>
<span class="k">internal</span> <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">TResult</span><span class="p">&gt;?</span> <span class="n">SafeSteamAPICall</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">TResult</span><span class="p">&gt;(</span><span class="n">Func</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">SteamAPICall_t</span><span class="p">&gt;</span> <span class="n">nativeCall</span><span class="p">,</span> <span class="n">T1</span> <span class="n">param1</span><span class="p">,</span> <span class="n">T2</span> <span class="n">param2</span><span class="p">);</span>
<span class="k">internal</span> <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">TResult</span><span class="p">&gt;?</span> <span class="n">SafeSteamAPICall</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">T3</span><span class="p">,</span> <span class="n">TResult</span><span class="p">&gt;(</span><span class="n">Func</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">T3</span><span class="p">,</span> <span class="n">SteamAPICall_t</span><span class="p">&gt;</span> <span class="n">nativeCall</span><span class="p">,</span> <span class="n">T1</span> <span class="n">param1</span><span class="p">,</span> <span class="n">T2</span> <span class="n">param2</span><span class="p">,</span> <span class="n">T3</span> <span class="n">param3</span><span class="p">);</span>
<span class="k">internal</span> <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">TResult</span><span class="p">&gt;?</span> <span class="n">SafeSteamAPICall</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">T3</span><span class="p">,</span> <span class="n">T4</span><span class="p">,</span> <span class="n">TResult</span><span class="p">&gt;(</span><span class="n">Func</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">T3</span><span class="p">,</span> <span class="n">T4</span><span class="p">,</span> <span class="n">SteamAPICall_t</span><span class="p">&gt;</span> <span class="n">nativeCall</span><span class="p">,</span> <span class="n">T1</span> <span class="n">param1</span><span class="p">,</span> <span class="n">T2</span> <span class="n">param2</span><span class="p">,</span> <span class="n">T3</span> <span class="n">param3</span><span class="p">,</span> <span class="n">T4</span> <span class="n">param4</span><span class="p">);</span>
<span class="k">internal</span> <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">TResult</span><span class="p">&gt;?</span> <span class="n">SafeSteamAPICall</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">T3</span><span class="p">,</span> <span class="n">T4</span><span class="p">,</span> <span class="n">T5</span><span class="p">,</span> <span class="n">TResult</span><span class="p">&gt;(</span><span class="n">Func</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">T3</span><span class="p">,</span> <span class="n">T4</span><span class="p">,</span> <span class="n">T5</span><span class="p">,</span> <span class="n">SteamAPICall_t</span><span class="p">&gt;</span> <span class="n">nativeCall</span><span class="p">,</span> <span class="n">T1</span> <span class="n">param1</span><span class="p">,</span> <span class="n">T2</span> <span class="n">param2</span><span class="p">,</span> <span class="n">T3</span> <span class="n">param3</span><span class="p">,</span> <span class="n">T4</span> <span class="n">param4</span><span class="p">,</span> <span class="n">T5</span> <span class="n">param5</span><span class="p">);</span>
<span class="k">internal</span> <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">TResult</span><span class="p">&gt;?</span> <span class="n">SafeSteamAPICall</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">T3</span><span class="p">,</span> <span class="n">T4</span><span class="p">,</span> <span class="n">T5</span><span class="p">,</span> <span class="n">T6</span><span class="p">,</span> <span class="n">TResult</span><span class="p">&gt;(</span><span class="n">Func</span><span class="p">&lt;</span><span class="n">T1</span><span class="p">,</span> <span class="n">T2</span><span class="p">,</span> <span class="n">T3</span><span class="p">,</span> <span class="n">T4</span><span class="p">,</span> <span class="n">T5</span><span class="p">,</span> <span class="n">T6</span><span class="p">,</span> <span class="n">SteamAPICall_t</span><span class="p">&gt;</span> <span class="n">nativeCall</span><span class="p">,</span> <span class="n">T1</span> <span class="n">param1</span><span class="p">,</span> <span class="n">T2</span> <span class="n">param2</span><span class="p">,</span> <span class="n">T3</span> <span class="n">param3</span><span class="p">,</span> <span class="n">T4</span> <span class="n">param4</span><span class="p">,</span> <span class="n">T5</span> <span class="n">param5</span><span class="p">,</span> <span class="n">T6</span> <span class="n">param6</span><span class="p">);</span>
</code></pre></div></div>

<p>C++ 이었으면 template parameter pack으로 쉽게 처리했을 부분인데, <a href="https://github.com/dotnet/roslyn/issues/5058">C# 엔 이게 없는 것으로 보인다.</a><br />
원래는 그냥 lambda로 매개변수를 죄다 캡쳐했었는데, <code class="language-plaintext highlighter-rouge">Span&lt;T&gt;</code>는 그게 불가능해서 울며 겨자 먹기로 저 지저분한 overload 방식으로 선회했다. 답이 없나?</p>

<p>질문글을 올리니 누가 <a href="https://github.com/WhiteBlackGoose/InductiveVariadics">이걸 자동 생성하는 Source Generator</a> 방식을 해법으로 주는데, 그건 좀…</p>

<h2 id="사용-예시">사용 예시</h2>

<p>GnsSharp의 <a href="https://github.com/nalchi-net/GnsSharp/blob/main/GnsSharp/ISteamRemoteStorage.cs"><code class="language-plaintext highlighter-rouge">ISteamRemoteStorage</code></a>를 이용해 Steam Cloud에서 파일을 읽어오는 예시</p>

<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">async</span> <span class="n">Task</span> <span class="nf">ReadSpacewarCloudFileAsync</span><span class="p">()</span>
<span class="p">{</span>
    <span class="kt">string</span> <span class="n">fileName</span> <span class="p">=</span> <span class="s">"message.dat"</span><span class="p">;</span>

    <span class="c1">// Assuming properly initialized, and running callback seperately</span>
    <span class="kt">var</span> <span class="n">storage</span> <span class="p">=</span> <span class="n">ISteamRemoteStorage</span><span class="p">.</span><span class="n">User</span><span class="p">!;</span>

    <span class="c1">// Get the file size first.</span>
    <span class="kt">int</span> <span class="n">size</span> <span class="p">=</span> <span class="n">storage</span><span class="p">.</span><span class="nf">GetFileSize</span><span class="p">(</span><span class="n">fileName</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">size</span> <span class="p">==</span> <span class="m">0</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">$"File '</span><span class="p">{</span><span class="n">fileName</span><span class="p">}</span><span class="s">' doesn't exist"</span><span class="p">);</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">$"Size of '</span><span class="p">{</span><span class="n">fileName</span><span class="p">}</span><span class="s">' was </span><span class="p">{</span><span class="n">size</span><span class="p">}</span><span class="s">"</span><span class="p">);</span>

    <span class="c1">// Start reading file asynchronously.</span>
    <span class="n">CallTask</span><span class="p">&lt;</span><span class="n">RemoteStorageFileReadAsyncComplete_t</span><span class="p">&gt;?</span> <span class="n">readTask</span>
        <span class="p">=</span> <span class="n">storage</span><span class="p">.</span><span class="nf">FileReadAsync</span><span class="p">(</span><span class="n">fileName</span><span class="p">,</span> <span class="m">0</span><span class="p">,</span> <span class="p">(</span><span class="kt">uint</span><span class="p">)</span><span class="n">size</span><span class="p">);</span>

    <span class="c1">// Skip if failed to start reading file.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">readTask</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">"File read not initiated"</span><span class="p">);</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// Await for reading to complete.</span>
    <span class="n">RemoteStorageFileReadAsyncComplete_t</span><span class="p">?</span> <span class="n">complete</span> <span class="p">=</span> <span class="k">await</span> <span class="n">readTask</span><span class="p">;</span>

    <span class="c1">// Skip if reading failed.</span>
    <span class="k">if</span> <span class="p">(!</span><span class="n">complete</span><span class="p">.</span><span class="n">HasValue</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">"File read not complete"</span><span class="p">);</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">complete</span><span class="p">.</span><span class="n">Value</span><span class="p">.</span><span class="n">Result</span> <span class="p">!=</span> <span class="n">EResult</span><span class="p">.</span><span class="n">OK</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">$"File read not complete: </span><span class="p">{</span><span class="n">complete</span><span class="p">.</span><span class="n">Value</span><span class="p">.</span><span class="n">Result</span><span class="p">}</span><span class="s">"</span><span class="p">);</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// Allocate buffer to copy the read bytes.</span>
    <span class="n">Span</span><span class="p">&lt;</span><span class="kt">byte</span><span class="p">&gt;</span> <span class="n">raw</span> <span class="p">=</span> <span class="k">stackalloc</span> <span class="kt">byte</span><span class="p">[(</span><span class="kt">int</span><span class="p">)</span><span class="n">complete</span><span class="p">.</span><span class="n">Value</span><span class="p">.</span><span class="n">ReadSize</span><span class="p">];</span>

    <span class="c1">// Copy the result to this buffer.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">storage</span><span class="p">.</span><span class="nf">FileReadAsyncComplete</span><span class="p">(</span><span class="n">complete</span><span class="p">.</span><span class="n">Value</span><span class="p">.</span><span class="n">FileReadAsync</span><span class="p">,</span> <span class="n">raw</span><span class="p">))</span>
    <span class="p">{</span>
        <span class="c1">// Assuming it's a UTF-8 string, print it.</span>
        <span class="kt">string</span> <span class="n">str</span> <span class="p">=</span> <span class="n">Encoding</span><span class="p">.</span><span class="n">UTF8</span><span class="p">.</span><span class="nf">GetString</span><span class="p">(</span><span class="n">raw</span><span class="p">);</span>
        <span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">$"Read string: </span><span class="p">{</span><span class="n">str</span><span class="p">}</span><span class="s">"</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">else</span>
    <span class="p">{</span>
        <span class="n">Console</span><span class="p">.</span><span class="nf">WriteLine</span><span class="p">(</span><span class="s">"FileReadAsyncComplete() failed"</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h1 id="참고-자료">참고 자료</h1>

<ul>
  <li><a href="https://devblogs.microsoft.com/dotnet/await-anything/">Stephen Toub - await anything;</a></li>
  <li><a href="https://www.jacksondunstan.com/articles/4918">JacksonDunstan.com - How Async and Await Work</a></li>
  <li><a href="https://vkontech.com/exploring-the-async-await-state-machine-the-awaitable-pattern/">Vasil Kosturski - Exploring the async/await State Machine – The Awaitable Pattern</a></li>
  <li><a href="https://www.dajbych.net/en/blog/how-to-write-a-custom-awaitable-method">Václav Dajbych - How to Write a Custom Awaitable Method</a></li>
  <li><a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2011/february/msdn-magazine-parallel-computing-it-s-all-about-the-synchronizationcontext">Stephen Cleary - It’s All About the SynchronizationContext</a></li>
</ul>

<p><em>마지막 수정 : 2025-05-03 14:38:00 +0900</em></p>]]></content><author><name>copyrat90</name></author><category term="C#" /><summary type="html"><![CDATA[C# 에서 async-await 패턴의 작동 방식과, 그를 이용한 custom awaitable 작성하기.]]></summary></entry></feed>