《Programming in Lua 3》读书笔记(八)

日期:2014.7.3
Coroutine(协同程序)
2014.7.10补充
(纯粹翻译书)
Lua中的协同程序类似于多线程概念中的线程:逐行执行,有自己独立的栈空间,自己的局部变量,自己的指令指针;但是Lua中的协同程序可以共享全局变量,并且可以多个协同程序间互相共享几乎任何变量。与线程最主要的区别在于:理论上讲,一个程序可以并行运行多个线程,但是Lua中的协同程序一次只能运行一个,并且协同程序只能在被明确挂起的时候挂起。  
看中文版的时候再了解一番。

2014.7.10补充
Lua将所有协同程序用到的函数都存储在一个叫做coroutine的table里面。

一些函数:
1、coroutine.create(param)             --创建一个协同程序
该函数带一个参数,参数为一个function,为协同程序要运行的函数;函数的返回值为一个thread类型的值,代表这个新创建的协同程序

e.g.
co = coroutine.create(function()
     return 6,7
end)
print(co)      --thread: 


--个人理解
刚创建的协同程序其状态是suspended的,挂起状态

2、coroutine.status(fun)       --返回fun的状态:running or suspended or dead or normal

e.g.
--此时打印其状态
coroutine.status(co)          --suspended


而coroutine.resume则运行这个
3、coroutine.resume(fun)      --运行fun

e.g.
coroutine.resume(co)          --true  6,7 返回true


coroutine.yield则只能在协同程序内部使用,在外部调用会报错
4、coroutine.yield(fun)          --转换fun状态,将其status从running转换到suspended
在协同程序内部使用,可以控制程序的运行

e.g.
co = coroutine.create(function ( ... )
     for i=1,10 do
          print(i)
     end    
end)
print(coroutine.status(co))          --suspended 
print(coroutine.resume(co))          --此时1 ~ 10 将全部会打印出来
print(coroutine.status(co))          --dead 

 

co = coroutine.create(function ( ... )
     for i=1,10 do
          print(i)
          coroutine.yield(co)
     end    
end)
print(coroutine.status(co))          --suspended 
print(coroutine.resume(co))     --此时只会打印 1      其状态转换为suspended
print(coroutine.status(co))          --suspended 
print(coroutine.resume(co))     --接着执行打印了1之后的下一步,打印出2
print(coroutine.status(co))          --suspended 



一个协同程序resume之后,其状态由suspended转换为running,运行完之后其状态变为dead,此时再resume则会返回false,指出 cannot resume dead coroutine

5、coroutine.wrap
创建一个coroutine,但是它并不返回coroutine本身,而是返回一个函数取而代之。该函数会返回所有应该由除第一个(错误代码的那个布尔量)之外的由coroutine.resume返回的值.该函数不捕获任何错误,所有的错误都由调用者自己传递。

具体的使用技术需进一步理解

posted @ 2014-07-11 13:29  Le Ciel  阅读(181)  评论(0编辑  收藏  举报