Lua - 使用队列链接协程
使用 Queue 可以大大简化协程的链接,并使它们变得松耦合。一个协程可以将消息发送到队列,而另一个协程可以在队列上等待以读取消息并相应地采取行动。
示例 - 使用队列进行链接
队列将作为协程之间消息的通道,如下所示:
定义队列以及发送/接收操作
-- queue as empty table
local queue = {}
-- send message will add a message to the queue
function send(message)
table.insert(queue, message)
end
-- to receive a message from Queue
function receive()
-- if queue has message
if #queue > 0 then
-- remove first entry and return the same
return table.remove(queue, 1)
end
-- yield the current coroutine if queue is empty
return coroutine.yield()
end
创建生产者和消费者协程函数
function Producer()
print("Producer Coroutine started")
send("Message 1 from producer")
coroutine.yield() -- yield the producer coroutine
send("Message 2 from producer")
print("Producer Coroutine finished")
end
function Consumer()
print("Consumer started")
local msg = receive() -- receive a message from queue
print("Consumer received:", msg)
coroutine.yield() -- yield the consumer coroutine
msg = receive() -- receive a message from queue
print("Consumer received:", msg)
print("Consumer Coroutine finished")
end
创建生产者和消费者协程并启动它们
-- create producer producer = coroutine.create(Producer) -- create consumer consumer = coroutine.create(Consumer) -- start producer coroutine.resume(producer) -- start consumer coroutine.resume(consumer) -- resume producer coroutine.resume(producer) -- resume consumer coroutine.resume(consumer)
完整示例 - 链接协程
main.lua
-- queue as empty table
local queue = {}
-- send message will add a message to the queue
function send(message)
table.insert(queue, message)
end
-- to receive a message from Queue
function receive()
-- if queue has message
if #queue > 0 then
-- remove first entry and return the same
return table.remove(queue, 1)
end
-- yield the current coroutine if queue is empty
return coroutine.yield()
end
function Producer()
print("Producer Coroutine started")
send("Message 1 from producer")
coroutine.yield() -- yield the producer coroutine
send("Message 2 from producer")
print("Producer Coroutine finished")
end
function Consumer()
print("Consumer started")
local msg = receive() -- receive a message from queue
print("Consumer received:", msg)
coroutine.yield() -- yield the consumer coroutine
msg = receive() -- receive a message from queue
print("Consumer received:", msg)
print("Consumer Coroutine finished")
end
-- create producer
producer = coroutine.create(Producer)
-- create consumer
consumer = coroutine.create(Consumer)
-- start producer
coroutine.resume(producer)
-- start consumer
coroutine.resume(consumer)
-- resume producer
coroutine.resume(producer)
-- resume consumer
coroutine.resume(consumer)
输出
运行上述代码时,将得到以下输出−
Producer Coroutine started Consumer started Consumer received: Message 1 from producer Producer Coroutine finished Consumer received: Message 2 from producer Consumer Coroutine finished
解释
这里 send() 函数将消息发送到队列。
receive() 函数从队列检索消息,如果队列为空则让协程 yield。
Producer 和 Consumer 协程通过队列进行通信。