国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

Lua協同程序函數coroutine使用實例

2024-07-21 23:04:07
字體:
來源:轉載
供稿:網友

協程是協同程序的簡稱,顧名思義,就是協同工作的程序。協程擁有自己獨立的桟、局部變量和PC計數器,同時又與其他協同程序共享全局變量和其他大部分東西;

協程與線程的主要區別在于,一個多線程程序可以同時運行幾個線程(并發執行、搶占),而協同程序卻需要彼此協作地運行,即一個多協程程序在任意時刻只能運行一個協程,并且正在執行的協程只會在其顯式地要求掛起(suspend)時,它的執行才會暫停(無搶占、無并發)。

 Lua中所有與協程相關的函數都在coroutine(一個table)中; 函數create用于創建新的協程,只有一個參數——要執行的函數,返回一個thread類型的值。

thread的狀態:suspend、running、dead、normal,可以通過coroutine.status(co)來檢查co的狀態。

創建一個thread時,它處于掛起狀態。coroutine.resume函數用于啟動或再次啟動一個協程的執行,并可以向coroutine傳遞參數。當一個協程結束時,主函數返回的值將作為resume的返回值。

coroutine.yield用于一個運行中的協程掛起(suspend),之后可以再恢復(resume)。yield的返回值就是resume傳入的參數。

Lua的協程模型可以類比Python的generator。

一個簡單的示例:

復制代碼 代碼如下:

> co = coroutine.create(function(a) while a > 0 do print(coroutine.yield(a)); a = a - 1; end return -1 end)
> return coroutine.resume(co, 3) --- 3是傳遞給主函數的
true        3
> return coroutine.resume(co, 4)
4
true        2
> return coroutine.resume(co, 5)
5
true        1
> return coroutine.resume(co, 6)
6
true        -1 ---主函數已經返回
> return coroutine.resume(co, 7)
false        cannot resume dead coroutine
>

 

協程的應用 —— 生產者/消費者

需求:輸入一行,打印一行

 

復制代碼 代碼如下:

function send(x)
coroutine.yield(x)
end
 
function receive(co)
local s, v = coroutine.resume(co)
return v
end
 
function producer()
return coroutine.create(function()
while true do
local x = io.read()
send(x)
end
end)
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
 
function consumer(prod)
while true do
local x = receive(prod)
io.write(x, '/n')
end
end
 
prod = producer()
fil = filter(prod)
con = consumer(fil)

協程的應用 —— 迭代器(類比Python Generator)
復制代碼 代碼如下:

function seq_generator(n)
local i = 1
while i <= n do
coroutine.yield(i)
i = i + 1
end
return nil
end
 
function seq(n)
local co = coroutine.create(function() seq_generator(n) end)
return function()
local s,v = coroutine.resume(co)
return v
end
end
 
for i in seq(4) do
print(i)
end

執行
復制代碼 代碼如下:

lua seq_generator.lua
1
2
3
4
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桂平市| 剑河县| 清水县| 聊城市| 西城区| 长武县| 汶川县| 临汾市| 越西县| 普洱| 黄骅市| 沅江市| 肥城市| 姚安县| 六枝特区| 黔南| 遂宁市| 永康市| 河池市| 南城县| 宜兰市| 开化县| 开江县| 太原市| 扶沟县| 宜川县| 内丘县| 吉水县| 马龙县| 忻城县| 庆云县| 惠安县| 盐池县| 古丈县| 兰西县| 汶川县| 宾川县| 桐梓县| 宾川县| 永福县| 冕宁县|