Producers and consumers
Two coroutines can pass data back and forth like a small pipeline.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to stop when the producer becomes dead
- Resuming without passing back needed values
- 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: