local coroutine_pool = { }
local coroutine_yield = coroutine.yield
local function dispatch(param)
print("function dispatch called", param)
end
local function resume_ret(...)
str = string.concat("...", " ")
print("resume ret ", str)
end
local global_co
local function co_create(f)
if global_co == nil then
print("ready to create coroutine")
global_co = coroutine.create(function(...)
f(x)
idx = 1
while true do
print("Idx ", idx)
idx = idx + 1
f = coroutine_yield "EXIT"
print("fffffffffff", type(f), f)
f(coroutine_yield())
print("f type", type(f), f)
end
end)
coroutine_pool[#coroutine_pool] = global_co
else
print("resume coroutine")
print(coroutine.resume(global_co, f))
end
return global_co
end
--print("disppppppppppppppppppatch ", dispatch)
print("create co11111111111111111111", co_create(dispatch))
print("create co22222222222222222222", co_create(dispatch))
print("create co33333333333333333333", co_create(dispatch))
结果
ready to create coroutine
create co11111111111111111111 thread: 0x8e60d0
resume coroutine
function dispatch called nil
Idx 1
true EXIT
create co22222222222222222222 thread: 0x8e60d0
resume coroutine
fffffffffff function function: 0x8e4b30
true
create co33333333333333333333 thread: 0x8e60d0
这个例子可以清晰的看出coroutine的工作原理和语义