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

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

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

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

多线程

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


--我的理解
刚建立的协同程序其状态是suspended的,挂起状态

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

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


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

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


coroutine.yield则只能在协同程序内部使用,在外部调用会报错
四、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

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

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

相关文章
相关标签/搜索