当前位置:   article > 正文

Lua 协同程序(coroutine)

Lua 协同程序(coroutine)

在 Lua 中,协同程序(coroutine)是一种轻量级的线程机制,允许程序在多个不同的控制点之间进行切换执行。协同程序在 Lua 中主要用于实现并发编程和协作式多任务处理。下面是如何在 Lua 中使用协同程序的示例和说明:

创建协同程序

在 Lua 中,你可以使用 coroutine.create 函数来创建一个新的协同程序。

示例
local co = coroutine.create(function()
    print("Hello from coroutine!")
end)
  • 1
  • 2
  • 3

启动协同程序

你可以使用 coroutine.resume 函数来启动一个协同程序。

示例
local co = coroutine.create(function()
    print("Hello from coroutine!")
end)

coroutine.resume(co)  -- 输出 "Hello from coroutine!"
  • 1
  • 2
  • 3
  • 4
  • 5

传递值

你可以通过 coroutine.resume 函数向协同程序传递值,并且可以从协同程序返回值。

示例
local co = coroutine.create(function(x, y)
    local sum = x + y
    print("Sum:", sum)
    return sum
end)

local result = coroutine.resume(co, 10, 5)
print("Result:", result)  -- 输出 "Result: 15"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

使用 yieldresume

协同程序可以通过 coroutine.yield 函数暂停执行,并且可以通过 coroutine.resume 继续执行。

示例
local co = coroutine.create(function()
    print("Coroutine started.")
    local x = coroutine.yield(10)
    print("Received:", x)
    coroutine.yield(20)
    print("Coroutine finished.")
end)

local status, x = coroutine.resume(co)
print("Status:", status, "X:", x)  -- 输出 "Status: true X: 10"
status, x = coroutine.resume(co, "Data")
print("Status:", status, "X:", x)  -- 输出 "Status: true X: Data"
status, x = coroutine.resume(co)
print("Status:", status, "X:", x)  -- 输出 "Coroutine finished." "Status: true X: 20"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

示例:使用协同程序实现生产者-消费者模型

下面是一个简单的示例,展示了如何使用协同程序来实现一个生产者-消费者模型。

local producer = coroutine.create(function(queue)
    print("Producer: Starting...")
    queue:put(1)
    queue:put(2)
    queue:put(3)
    print("Producer: Finished.")
end)

local consumer = coroutine.create(function(queue)
    print("Consumer: Starting...")
    while true do
        local item = queue:get()
        if item == nil then
            break
        end
        print("Consumer: Got item:", item)
    end
    print("Consumer: Finished.")
end)

local Queue = {}
Queue.__index = Queue

function Queue:new()
    local q = setmetatable({items = {}}, Queue)
    return q
end

function Queue:put(item)
    table.insert(self.items, item)
end

function Queue:get()
    if #self.items > 0 then
        return table.remove(self.items, 1)
    else
        return nil
    end
end

local queue = Queue:new()
coroutine.resume(producer, queue)
coroutine.resume(consumer, queue)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

在这个示例中,我们创建了一个简单的队列来存储项,并使用两个协同程序来模拟生产者和消费者的行为。

示例:使用协同程序实现简单的任务调度

下面是一个简单的示例,展示了如何使用协同程序来实现一个简单的任务调度器。

local TaskScheduler = {}
TaskScheduler.__index = TaskScheduler

function TaskScheduler:new()
    local scheduler = setmetatable({
        tasks = {},
        current = nil
    }, TaskScheduler)
    return scheduler
end

function TaskScheduler:add(task)
    table.insert(self.tasks, task)
end

function TaskScheduler:run()
    while #self.tasks > 0 do
        local task = self.tasks[1]
        table.remove(self.tasks, 1)
        self.current = task
        coroutine.resume(task)
        self.current = nil
    end
end

function TaskScheduler:yield()
    if self.current then
        coroutine.yield()
    end
end

local scheduler = TaskScheduler:new()

local task1 = coroutine.create(function()
    print("Task 1: Started.")
    scheduler:yield()
    print("Task 1: Finished.")
end)

local task2 = coroutine.create(function()
    print("Task 2: Started.")
    scheduler:yield()
    print("Task 2: Finished.")
end)

scheduler:add(task1)
scheduler:add(task2)
scheduler:run()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

在这个示例中,我们创建了一个简单的任务调度器,它可以添加任务并运行它们。每个任务都会调用 scheduler:yield() 来让出执行权给其他任务。

这些是在 Lua 中使用协同程序的基本概念和示例。协同程序提供了一种简单而强大的方式来实现并发编程。如果您需要更详细的解释或有其他问题,请随时提问!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/963957
推荐阅读
相关标签
  

闽ICP备14008679号

        
cppcmd=keepalive&