1、基础
所有协程相关的在表coroutine中,创建通过create来创建,参数为函数,返回值类型为thread.
协程状态有:suspended, running, normal, dead。通过coroutine.status获取协程状态。
create创建的协程初始状态为suspened,通过coroutine.resume来启动执行,协程状态变为running
暂停协程使用coroutine.yield,返回传递的参数
co = coroutine.create(function(x)
print("co1", x)
print("co2", coroutine.yield())
end)
coroutine.resume(co, "hi")
coroutine.resume(co, 4, 5)
输出为:
co1 hi
co2 4 5
使用consume执行协程时,并且传递参数,如果协程内使用yield,执行时返回传递的参数。
co = coroutine.create(function(a, b)
coroutine.yield(a + b, a - b)
end)
print(coroutine.resume(co, 1, 2))
输出为:
true 3 -1
生产-消费模型
function producer()
while true do
local x = io.read()
send(x)
end
end
function consumer()
while true do
local x = receive()
io.write(x, "\n")
end
end
function receive()
local status, value = coroutine.resume(producer())
return value
end
function send(x)
coroutine.yield(x)
end
pro = coroutine.create(producer)
带有过滤功能的生产-消费模型
function producer()
return coroutine.create(function()
while true do
local x = io.read()
send(x)
end
end)
end
function consumer(prod)
while true do
local x = receive(prod)
io.write(x, "\n")
end
end
function receive(prod)
local status, value = coroutine.resume(prod)
return value
end
function send(x)
coroutine.yield(x)
end
function filter(prod)
return coroutine.create(function()
for line = 1, math.huge do
local x = receive(prod)
x = string.format("%5d %s", line, x)
send(x)
end
end)
end
consumer(filter(producer()))
2、协程作为迭代器
不使用协程生成排列
function permgen(a, n)
n = n or #a
if n <= 1 then
printResult(a)
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
function printResult(a)
for i = 1, #a do io.write(a[i], " ") end
io.write("\n")
end
permgen({1, 2, 3, 4})
使用协程生成排列
function permgen(a, n)
n = n or #a
if n <= 1 then
coroutine.yield(a)
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
function printResult(a)
for i = 1, #a do io.write(a[i], " ") end
io.write("\n")
end
function permutations(a)
local co = coroutine.create(function() permgen(a) end)
return function()
local code, res = coroutine.resume(co)
return res
end
end
for p in permutations{"a", "b", "c"} do
printResult(p)
end