0Pricing
Lua Academy · 강의

생산자-소비자 패턴

코루틴을 사용해 생산자-소비자 파이프라인을 구현합니다.

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

패턴 설명

코루틴을 사용하는 생산자-소비자 패턴에서는 생산자가 데이터를 생성하고 각 항목을 yield하며, 소비자가 항목을 한 번에 하나씩 받습니다. 두 구성 요소는 서로의 구현을 알 필요 없이 yield/resume을 통해 통신합니다. 이를 통해 데이터 생성을 데이터 처리와 분리할 수 있습니다.

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

local function consume(producer)
  while true do
    local ok, item = coroutine.resume(producer)
    if not ok or item == nil then break end
    print("Processing:", item)
  end
end

consume(makeProducer({10, 20, 30, 40}))

무한 생산자

생산자 코루틴은 무한한 시퀀스를 yield할 수 있습니다. 중지 시점은 소비자가 제어합니다. 센서 측정값, 로그 이벤트, 생성된 시퀀스와 같은 스트리밍 데이터 소스에 적합합니다.

local function primes()
  return coroutine.wrap(function()
    local function isPrime(n)
      if n<2 then return false end
      for i=2, math.floor(math.sqrt(n)) do
        if n%i==0 then return false end
      end
      return true
    end
    local n = 2
    while true do
      if isPrime(n) then coroutine.yield(n) end
      n = n + 1
    end
  end)
end

local gen = primes()
for i = 1, 10 do
  io.write(gen() .. " ")
end
print()  -- 2 3 5 7 11 13 17 19 23 29

코루틴으로 동작하는 소비자

소비자도 코루틴으로 만들 수 있으므로 완전히 대칭적인 생산자-소비자 쌍을 구성할 수 있습니다. 세 번째 "구동" 함수가 두 코루틴을 조정합니다. 생산자와 소비자의 처리 속도가 다른 버퍼링된 파이프라인에 유용합니다.

local function producer()
  return coroutine.create(function(consumer)
    for i = 1, 5 do
      coroutine.resume(consumer, i * 10)
      coroutine.yield()  -- wait
    end
  end)
end

local consumer = coroutine.create(function()
  while true do
    local val = coroutine.yield()
    print("Received:", val)
  end
end)

coroutine.resume(consumer)  -- start, waits for data
local pro = producer()
for i = 1, 5 do
  coroutine.resume(pro, consumer)
end

역압

역압은 소비자가 생산자에게 속도를 늦추라는 신호를 보내는 현상입니다. 코루틴에서는 이것이 자연스럽게 이루어집니다. 생산자는 각 항목 후에 yield하여 소비자가 다음 항목을 요청할 때까지 기다립니다. 소비자가 느리면 생산자는 그대로 기다립니다.

local function slowConsumer(gen)
  for v in gen do
    -- Simulate slow processing
    print("Processing", v, "...")
    -- In real code: os.execute("sleep 0.1")
  end
end

local function fastProducer(n)
  return coroutine.wrap(function()
    for i = 1, n do
      print("Producing", i)
      coroutine.yield(i)
    end
  end)
end

-- Producer automatically waits for consumer:
slowConsumer(fastProducer(4))

일괄 처리

일괄 처리 생산자는 N개의 항목을 모은 후 하나의 묶음으로 yield합니다. 소비자는 완성된 묶음을 받아 처리합니다. 이를 통해 빈번하게 항목을 생성하는 생산자의 조정 오버헤드를 줄일 수 있습니다.

local function batchProducer(items, batchSize)
  return coroutine.wrap(function()
    local batch = {}
    for _, item in ipairs(items) do
      batch[#batch+1] = item
      if #batch >= batchSize then
        coroutine.yield(batch)
        batch = {}
      end
    end
    if #batch > 0 then coroutine.yield(batch) end
  end)
end

local data = {1,2,3,4,5,6,7,8,9,10}
for batch in batchProducer(data, 3) do
  print("Batch:", table.concat(batch, ","))
end
-- Batch: 1,2,3
-- Batch: 4,5,6
-- Batch: 7,8,9
-- Batch: 10

파일 줄 생산자

파일을 지연 방식으로 읽을 수 있습니다. 생산자 코루틴이 한 번에 한 줄씩 읽고 각 줄을 yield합니다. 소비자는 파일 전체를 메모리에 로드하지 않고 줄을 처리합니다.

local function lineProducer(path)
  return coroutine.wrap(function()
    local f = io.open(path, "r")
    if not f then return end
    for line in f:lines() do
      coroutine.yield(line)
    end
    f:close()
  end)
end

-- Process file line by line without loading all at once
local wordCount = 0
for line in lineProducer("data.txt") do
  for _ in line:gmatch("%S+") do
    wordCount = wordCount + 1
  end
end
print("Words:", wordCount)

변환 단계

생산자와 소비자 사이에 변환 단계를 삽입하십시오. 변환 단계는 한 코루틴에서 읽고 처리된 값을 다른 코루틴으로 yield합니다. 이러한 단계를 연결하여 데이터 파이프라인을 구성할 수 있습니다.

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

local numbers = coroutine.wrap(function()
  for i = 1, 6 do coroutine.yield(i) end
end)

local doubled = transform(numbers, function(n) return n*2 end)
local filtered = coroutine.wrap(function()
  for v in doubled do
    if v > 4 then coroutine.yield(v) end
  end
end)

for v in filtered do io.write(v.." ") end
print()  -- 6 8 10 12

파이프라인의 오류 전파

코루틴 파이프라인의 오류는 종료 상태나 pcall을 통해 전파됩니다. 파이프라인 전체가 중단되지 않도록 파이프라인 단계를 pcall로 감싸 오류를 포착하고 적절히 처리하십시오.

local function safeStage(source, fn)
  return coroutine.wrap(function()
    for v in source do
      local ok, result = pcall(fn, v)
      if ok then
        coroutine.yield(result)
      else
        print("Error processing", v, ":", result)
      end
    end
  end)
end

local data = coroutine.wrap(function()
  for _, v in ipairs({4, -1, 9, 0, 16}) do coroutine.yield(v) end
end)

local results = safeStage(data, function(n)
  assert(n > 0, "non-positive")
  return math.sqrt(n)
end)

for v in results do print(v) end

생산자 병합

여러 생산자를 하나로 결합할 수 있습니다. 아직 살아 있는 모든 생산자를 라운드 로빈 방식으로 순회하며 각 항목을 차례로 yield합니다. 모든 생산자가 소진되면 중지합니다.

local function merge(...)
  local producers = {...}
  return coroutine.wrap(function()
    while #producers > 0 do
      local alive = {}
      for _, co in ipairs(producers) do
        local ok, v = coroutine.resume(co)
        if ok and v ~= nil then
          coroutine.yield(v)
          alive[#alive+1] = co
        end
      end
      producers = alive
    end
  end)
end

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

for v in merge(src({1,3,5}),src({2,4,6})) do
  io.write(v.." ")
end
print()  -- 1 2 3 4 5 6

실제 사용 사례

로그 처리 파이프라인의 예입니다. 생산자가 로그 줄을 읽고, 필터 단계가 오류 줄만 남기며, 변환 단계가 핵심 정보를 추출하고, 소비자가 오류 유형별로 집계합니다. 각 단계는 독립적으로 테스트할 수 있는 코루틴입니다.

local function makeFilter(src, pred)
  return coroutine.wrap(function()
    for line in src do
      if pred(line) then coroutine.yield(line) end
    end
  end)
end

local logs = coroutine.wrap(function()
  local entries = {
    "INFO: started",
    "ERROR: timeout",
    "DEBUG: connecting",
    "ERROR: auth failed",
  }
  for _, e in ipairs(entries) do coroutine.yield(e) end
end)

local errors = makeFilter(logs, function(l) return l:match("^ERROR") end)
for line in errors do print(line) end
-- ERROR: timeout
-- ERROR: auth failed

빠른 확인

생산자-소비자 코루틴 패턴은 역압을 어떻게 처리합니까?

복습: 생산자-소비자

요약:

  • 생산자는 항목을 yield하고, 소비자는 resume을 호출하여 실행을 이끕니다
  • 무한 생산자: while true do yield() end
  • 파이프라인: 생산자와 소비자 사이에 변환 코루틴을 연결합니다
  • 역압은 자동으로 처리됩니다. 생산자가 소비자를 기다립니다
  • 일괄 처리, 필터, 병합 단계를 코루틴 래퍼로 구성할 수 있습니다
  • 오류를 격리하려면 파이프라인 단계에서 pcall을 사용하십시오

자주 묻는 질문

“생산자-소비자 패턴” 강의는 무료인가요?

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

“생산자-소비자 패턴”에서 뭘 배우나요?

코루틴을 사용해 생산자-소비자 파이프라인을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Lua Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“생산자-소비자 패턴” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

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