3.3 Lua代码中的协程
什么是协程?
协程是一种用户态的轻量级线程,由用户控制调度。与操作系统线程不同:
- 协程由程序显式控制切换 
- 开销极小,可创建成千上万个 
- 协作式调度,不会出现竞态条件 
常用的协程API
coroutine.close (co) --- 关闭协程,返回bool
coroutine.create (f) --- 创建协程,传入一个function,返回一个协程句柄
coroutine.isyieldable ([co]) --- 判断协程是否是 yield 状态
coroutine.resume (co [, val1, ...]) --- 将挂起态的协程重新激活
coroutine.running () --- 获取正在运行的协程
coroutine.status (co) --- 获取co句柄对应的协程的状态 {suspended(挂起), running(执行中), dead(结束)}
coroutine.wrap (f) --- 用function 创建一个新的协程
coroutine.yield (...) --- 挂起当前协程示例代码:
function myprint(a,b)print("协程",a,b);print("协程状态:",coroutine.status(handle1));coroutine.yield(1,2);
endhandle1=coroutine.create(myprint);--创建协程print(coroutine.status(handle1));--获取当前协程的状态print(coroutine.resume(handle1,123,999));--开始执行该协程print(coroutine.status(handle1));coroutine.close(handle1);print(coroutine.status(handle1));print(coroutine.running());运行结果:
suspended
协程	123	999
协程状态:	running
true	1	2
suspended
dead
thread: 00000000006f6ca8	true双循环切换
function sleep(seconds)local start = os.time()while os.time() - start < seconds do-- 空循环,占用 CPUendendfunction myprint1()while true docoroutine.resume(handle2);print("func1--111");sleep(1);end
endfunction myprint2()while true docoroutine.yield();print("func2---222");sleep(1);endendhandle1=coroutine.create(myprint1);--创建协程
handle2=coroutine.create(myprint2);--创建协程coroutine.resume(handle1);运行结果:
func1--111
func2---222
func1--111
func2---222
func1--111
func2---222
func1--111
func2---222