lua中協程的建立和使用

2021-10-10 05:50:52 字數 2506 閱讀 4927

協程:協程有三個狀態,掛起、執行,死亡

協程與多執行緒情況下得執行緒比較類似,有自己的堆疊,自己的區域性變數,有自己的指標指令,但與其他協同程式共享全域性變數等很多資訊。執行緒和協程的主要不同在於:在多處理器情況下,從概念上來講多執行緒程式同時可以執行多個執行緒,而協程是通過協作來完成,在任意指定時刻只有乙個協程在執行,並且這個正在執行的協程只有在必要時才會被掛起

coroutine.create() 建立並返回協程,引數時乙個函式,和resume配合使用時就會喚醒函式呼叫

coroutine.resume(co, val1, ...)  重啟協程,配合create一起使用

coroutine.yield() 掛起協程,經協程設定為掛起狀態,和resume配合使用

coroutine.status() 檢視協程的三種狀態

coroutine.wrap() 建立協程,返回乙個函式,一旦呼叫這個函式,就進入corotine和creat功能重複

coroutine.running()返回正在跑的coroutine,當呼叫running的時候,就是返回也coroting得執行緒號

建立和喚醒函式的使用

co = coroutine.create(

function (i)

print(i)

end)--使用resume將這個協程喚醒

coroutine.resume(co,2) --輸出 2

--喚醒執行完之後,協程進入死亡狀體

print(coroutine.status(co)) --輸出dead

建立、喚醒,掛起,檢視狀態函式的使用

--建立乙個協程

co1 = coroutine.create(

function ()

for i = 1, 10, 1 do

print(i)

if i == 3 then

--檢視當前得狀態,此時正在執行中

print(coroutine.status(co1)) --輸出running

print(coroutine.running()) --輸出 thread:******

end--掛起當前協程,在掛起之後需要重新喚醒當前協程

coroutine.yield()

endend

)coroutine.resume(co1)

coroutine.resume(co1)

coroutine.resume(co1)

print(coroutine.status(co1)) --輸出是掛起狀態

建立協程並返回乙個函式

--建立乙個協程,並返回乙個函式

co2 = coroutine.wrap(

function ()

for i = 1, 10, 2 do

print(string.format("%d = %d",i,i))

endend

)print(coroutine.running())

co2()

function foo(a)

print("foo 函式輸出:",a)

return coroutine.yield(2 * a)

endco3 = coroutine.create(function (a,b)

print("第一次協程執行輸出:",a,b)

local r = foo(a + 1)

print("第二次協程執行輸出:",r)

local r,s = coroutine.yield(a + b,a - b)

print("第三次協程執行輸出:",r,s)

return b, "結束協程"

end)

print(coroutine.resume(co3,10,1))

print(coroutine.resume(co3,"w"))

print(coroutine.resume(co3,"s","q"))

local newproductor

function productor()

local i = 0

while true do

i = i + 1

send(i)

endendfunction consumer()

while true do

local i = receive()

print(i)

endendfunction receive()

local status,value = coroutine.resume(newproductor)

return value

endfunction send(x)

coroutine.yield(x)

endnewproductor = coroutine.create(productor)

consumer()

Lua中使用協程

前一段時間在寫遊戲裡的 介面,會用到計時器,所以學了一點關於lua中關於協程的用法,記錄下來給大家分享 首先我們要了解一下協程的生命週期,乙個協程有四種狀態 掛起 suspended 執行 running 死亡 dead 和正常 normal 我們先建立乙個簡單的協程 local co corout...

Lua的協程基礎

參考 lua中的協同程式 coroutine 協同程式 coroutine 三個狀態 suspended 掛起,協同剛建立完成時或者yield之後 running 執行 dead 函式走完後的狀態,這時候不能再重新resume coroutine.create arg 根據乙個函式建立乙個協同程式,...

Lua中的協程coroutine簡介

lua中的協程coroutine lua中的協程有自己的堆疊,自己的區域性變數,有自己的指令指標,但是和其他協程程式共享全域性變數等資訊。任何時刻只有乙個協程程式在執行。並且這個在執行的協程只有明確被要求掛起時才會被掛起。建立乙個協程,引數是乙個function,作用如thread local c ...