Reputation: 45
This is the consumer-producer , producer as coroutine and consumer as main thread:
function receive (prod)
local status, value = coroutine.resume(prod)
return value
end
function send (x)
coroutine.yield(x)
end
function producer ()
return coroutine.create(function ()
while true do
local x = io.read()
-- produce new value
send(x)
end
end)
end
function filter (prod)
return coroutine.create(function ()
for line = 1, math.huge do
local x = receive(prod)
-- get new value
x = string.format("%5d %s", line, x)
send(x)
-- send it to consumer
end
end)
end
function consumer (prod)
while true do
local x = receive(prod)
io.write(x, "\n")
end
end
-- get new value
-- consume new value
consumer(filter(producer()))
and here is my answer bt is not running as expected:
function receive (x)
coroutine.yield(x)
end
function send (cons, x)
local status, value = coroutine.resume(cons, x)
return value
end
function producer (cons)
while true do
local x = io.read()
-- produce new value
send(cons, x)
end
end
function filter (cons)
return coroutine.create(function (x)
for line = 1, math.huge do
local _, x = receive(x)
-- get new value
x = string.format("%5d %s", line, x)
send(cons, x)
-- send it to consumer
end
end)
end
function consumer ()
return coroutine.create(function(x)
while true do
local x = receive(x)
io.write(x, "\n")
end
end)
end
-- get new value
-- consume new value
producer(filter(consumer()))
Thing is while getting into local x = receive(x) into filter() function, then it is going again to producer() waiting for new input wthout formating x input. Any suggestion? I do not want to change the initial way was implemented, meaning the recieve() bound into the consumer() and send() bound into reciever().
Upvotes: 0
Views: 53
Reputation: 1539
The receiver isn't returning anything, let's add a return.
function receive(x)
return coroutine.yield(x)
end
The receiver only returns one value in your example, let's remove _
.
local x = receive(x)
Then all your consumer, filter etc are one input delayed because you ignore the first x, and then enter the loop.
Upvotes: 0