Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created November 17, 2012 13:25
Show Gist options
  • Save hpcx82/4095981 to your computer and use it in GitHub Desktop.
Save hpcx82/4095981 to your computer and use it in GitHub Desktop.
use coroutine to implement producer-consumer
function consumer(prod)
while true do
local x = receive(prod)
print(x)
end
end
function receive(prod)
local status, value = coroutine.resume(prod)
return value
end
function send(x)
coroutine.yield(x) -- go back to where resumed
end
function producer()
return coroutine.create(function()
while true do
local x = io.read()
send(x)
end
end)
end
-- consumer-driven design
consumer(producer())
function produce()
return io.read()
end
function consume(x)
print(x)
end
while true do
local x = produce()
consume(x)
end
function send(a)
coroutine.yield(a)
end
function receive(prod)
local status, value = coroutine.resume(prod)
return value
end
function consumer(prod)
local function print_result(a)
for _, v in ipairs(a) do
io.write(v, " ")
end
io.write('\n')
end
while true do
local a = receive(prod)
if not a then break end
print_result(a)
end
end
function producer(a)
function permgen(a, n)
if n == 0 then
send(a) -- send something for consuming from an recursive call
else
for i=1, n do
a[n], a[i] = a[i], a[n]
permgen(a, n-1)
a[n], a[i] = a[i], a[n]
end
end
end
local n = table.getn(a)
return coroutine.create(function() permgen(a, n) end)
end
consumer(producer({1,2,3,4}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment