0Pricing
Lua Academy · 강의

resume과 yield

resume/yield로 호출자와 코루틴 사이에 데이터를 주고받습니다.

resume과 yield은(는) CoddyKit의 무료 Lua Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Lua Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

코루틴에 값 전달

첫 번째 coroutine.resume에 전달된 인수는 코루틴 본문의 함수 매개변수가 됩니다. 그 이후의 재개 호출에 전달된 인수는 코루틴을 일시 중단한 coroutine.yield() 호출의 반환값이 됩니다.

local co = coroutine.create(function(a, b)
  print("received:", a, b)        -- 10  20
  local c = coroutine.yield()     -- pauses
  print("after yield:", c)        -- 30
end)

coroutine.resume(co, 10, 20)  -- first call: passes a,b
coroutine.resume(co, 30)      -- subsequent: passed to yield

yield에서 전달되는 값

coroutine.yield(val1, val2)에 전달된 값은 yield에서 일시 중단된 coroutine.resume() 호출의 반환값이 됩니다. 즉, yield는 호출자에게 값을 "반환"합니다.

local co = coroutine.create(function()
  coroutine.yield(1, "hello")
  coroutine.yield(2, "world")
  return 3, "done"
end)

local ok, a, b = coroutine.resume(co)
print(ok, a, b)   -- true  1  hello

ok, a, b = coroutine.resume(co)
print(ok, a, b)   -- true  2  world

ok, a, b = coroutine.resume(co)
print(ok, a, b)   -- true  3  done

양방향 통신

코루틴을 사용하면 진정한 양방향 통신이 가능합니다. 호출자는 resume을 통해 데이터를 전달하고, 코루틴은 데이터를 처리한 후 결과를 yield로 돌려줍니다. 각 resume/yield는 동기식 교환입니다.

local co = coroutine.create(function(x)
  while true do
    x = coroutine.yield(x * x)  -- yield x^2, get next x
  end
end)

coroutine.resume(co)  -- start (x=nil initially)
local ok, sq
ok, sq = coroutine.resume(co, 3); print(sq)  -- 9
ok, sq = coroutine.resume(co, 5); print(sq)  -- 25
ok, sq = coroutine.resume(co, 7); print(sq)  -- 49

생산자-소비자

코루틴의 대표적인 패턴입니다. 생산자는 항목을 한 번에 하나씩 yield하고, 소비자는 다음 항목이 필요할 때마다 생산자를 재개합니다. 어느 쪽도 다른 쪽보다 앞서 실행되지 않으므로 완벽하게 동기화됩니다.

local function producer(items)
  return coroutine.create(function()
    for _, item in ipairs(items) do
      coroutine.yield(item)
    end
  end)
end

local pro = producer({"apple","banana","cherry"})

-- Consumer drives the loop
while true do
  local ok, item = coroutine.resume(pro)
  if not ok or item == nil then break end
  print("consumed:", item)
end

코루틴을 사용한 파이프라인

여러 코루틴을 파이프라인으로 연결할 수 있습니다. 각 단계는 이전 단계에서 읽고 다음 단계로 yield합니다. 마지막 단계가 마지막 코루틴을 재개하여 파이프라인을 구동하면, 그 동작이 연결을 따라 앞쪽 단계로 연쇄적으로 전달됩니다.

local function source(items)
  return coroutine.wrap(function()
    for _, v in ipairs(items) do coroutine.yield(v) end
  end)
end

local function filter(iter, pred)
  return coroutine.wrap(function()
    for v in iter do
      if pred(v) then coroutine.yield(v) end
    end
  end)
end

local function map(iter, fn)
  return coroutine.wrap(function()
    for v in iter do coroutine.yield(fn(v)) end
  end)
end

local pipeline = map(filter(source({1,2,3,4,5,6}),
  function(n) return n%2==0 end),
  function(n) return n*n end)

for v in pipeline do io.write(v.." ") end
print()  -- 4 16 36

비동기 작업 시뮬레이션에 코루틴 사용

OS 스레드가 없어도 코루틴으로 비동기 작업을 시뮬레이션할 수 있습니다. "대기"하는 동안 yield하고 "결과"가 준비되면 resume합니다. 스케줄러가 결과와 함께 코루틴을 재개합니다.

local scheduler = {}
local current = nil

local function await(key)
  coroutine.yield(key)  -- tell scheduler what we need
  return coroutine.yield()  -- wait for result
end

local co = coroutine.create(function()
  local data = await("fetch:users")
  print("Got users:", data)
end)

-- Start coroutine
local ok, want = coroutine.resume(co)
print("Coroutine wants:", want)  -- fetch:users
-- Simulate delivering the result:
coroutine.resume(co, {{name="Alice"},{name="Bob"}})

함수 내부의 yield

최상위 함수뿐 아니라 코루틴이 호출한 어떤 함수 내부에서도 yield할 수 있습니다. yield는 중첩된 모든 호출을 거쳐 resume 호출까지 전달됩니다. 이를 "일시 중단된 호출 스택"이라고 합니다.

local function yieldTwice(label)
  coroutine.yield(label .. ":1")
  coroutine.yield(label .. ":2")
end

local co = coroutine.create(function()
  yieldTwice("A")
  yieldTwice("B")
end)

for i = 1, 4 do
  local ok, v = coroutine.resume(co)
  print(v)
end
-- A:1, A:2, B:1, B:2

코루틴은 스레드가 아닙니다

Lua 코루틴은 OS 스레드가 아닙니다. 한 번에 하나의 코루틴만 실행되며 선점이나 병렬 실행은 없습니다. 모든 코루틴은 하나의 OS 스레드를 공유합니다. 진정한 병렬 실행이 필요하다면 서로 다른 OS 스레드에서 여러 Lua 상태를 사용해야 합니다.

-- This is NOT parallel - interleaved execution
local function task(name, n)
  for i = 1, n do
    print(name, i)
    coroutine.yield()
  end
end

local t1 = coroutine.create(function() task("A", 3) end)
local t2 = coroutine.create(function() task("B", 3) end)

-- Must explicitly schedule:
for _ = 1, 3 do
  coroutine.resume(t1)
  coroutine.resume(t2)
end
-- A1, B1, A2, B2, A3, B3 (interleaved, NOT parallel)

재개 후 상태

다시 재개할지 결정하려면 코루틴 상태를 확인하십시오. 실행을 마친 코루틴(본문에서 반환된 코루틴)은 "종료" 상태이며, 이를 재개하면 오류와 함께 false가 반환됩니다. 반복문에서 재개하기 전에는 항상 상태를 확인하십시오.

local co = coroutine.create(function()
  for i = 1, 3 do coroutine.yield(i) end
end)

while coroutine.status(co) ~= "dead" do
  local ok, val = coroutine.resume(co)
  if ok and val ~= nil then
    print("val:", val)
  end
end
-- val: 1, val: 2, val: 3

한 번의 resume에서 여러 번 yield하기

coroutine.resume을 한 번 호출하면 코루틴은 다음 yield에 도달하거나 종료될 때까지 실행됩니다. 한 번의 resume에서 코루틴이 여러 번 yield하도록 만들 수는 없습니다. 각 yield는 코루틴을 일시 중단하고 다음 resume을 기다리게 합니다.

local co = coroutine.create(function()
  local x = coroutine.yield("first")
  print("got:", x)
  local y = coroutine.yield("second")
  print("got:", y)
end)

local _, v1 = coroutine.resume(co)         -- starts, yields "first"
print("yielded:", v1)                       -- first
local _, v2 = coroutine.resume(co, "a")   -- passes "a", yields "second"
print("yielded:", v2)                       -- second
coroutine.resume(co, "b")                   -- passes "b", coroutine ends

빠른 확인

coroutine.yield(v1, v2)에 전달된 값은 무엇이 됩니까?

복습: resume과 yield

요약:

  • 첫 번째 resume 인수 → 코루틴 본문의 매개변수
  • 이후 resume 인수 → 이전 yield()가 반환
  • yield 인수 → yield를 발생시킨 resume()이 반환
  • 양방향: 각 resume/yield는 하나의 교환입니다
  • 중첩된 어떤 함수에서든 yield할 수 있습니다
  • 코루틴은 협력적으로 실행되며 병렬 실행되지 않습니다

자주 묻는 질문

“resume과 yield” 강의는 무료인가요?

네 — “resume과 yield” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Lua Academy 강의 전체를 잠금 해제할 수 있습니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“resume과 yield”에서 뭘 배우나요?

resume/yield로 호출자와 코루틴 사이에 데이터를 주고받습니다. 브라우저에서 직접 실행하는 실습 코드로 Lua Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Lua Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Lua Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“resume과 yield” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Lua Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Lua Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 코루틴 만들기
  2. resume과 yield
  3. 코루틴 상태
  4. 생산자-소비자 패턴
← Lua Academy(으)로 돌아가기