Created
November 29, 2014 09:56
-
-
Save qi7chen/07604607729373e63ebe to your computer and use it in GitHub Desktop.
lua coroutine producer/consumer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local coroutine = coroutine | |
local function receive(p) | |
local s, value = coroutine.resume(p) | |
return value | |
end | |
local function send(x) | |
coroutine.yield(x) | |
end | |
local function producer() | |
return coroutine.create(function () | |
while true do | |
local x = io.read() | |
send(x) | |
end | |
end) | |
end | |
local function filter(p) | |
return coroutine.create(function() | |
for line = 1, math.huge do | |
local x = receive(p) | |
x = string.format('%03d %s', line, x) | |
send(x) | |
end | |
end) | |
end | |
local function consumer(p) | |
while true do | |
local x = receive(p) | |
if x then | |
print(x) | |
end | |
end | |
end | |
print('enter:') | |
consumer(filter(producer())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment