← Back to Lua Course | Chapter 7: Coroutines | Lesson 6 of 7

Producers and consumers

Two coroutines can pass data back and forth like a small pipeline.

In this page:

  1. Producers and consumers

Producers and consumers

In the producer-consumer pattern one part generates data and another processes it. With coroutines the producer yields each item and a consumer loop resumes it and handles what comes back. A filter can sit in the middle as another coroutine, which forms a pipeline without any threads.

Note: A coroutine that returns normally ends with resume returning true and its return values.

Example: Producers and consumers

lua
local function producer()
  return coroutine.create(function()
    for _, w in ipairs({"alpha", "beta", "gamma"}) do
      coroutine.yield(w)
    end
  end)
end

local function consumer(p)
  local out = {}
  while true do
    local ok, item = coroutine.resume(p)
    if not item then break end
    out[#out + 1] = item:upper()
  end
  return out
end
print(table.concat(consumer(producer()), ", "))

-- Output:
-- ALPHA, BETA, GAMMA
Common Mistakes
  1. Forgetting to stop when the producer becomes dead
  2. Resuming without passing back needed values
  3. Mixing up which side is producer and which is consumer
Chapter Summary
  • The producer yields items
  • The consumer resumes to get them
  • Filters can be chained
  • Check status or nil to stop
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.