zoukankan      html  css  js  c++  java
  • Lua协程的一个例子

    很久没记录笔记了,还是养成不了记录的习惯

    下面是来自 programming in lua的一个协程的例(生产者与用户的例子)

    帖代码,慢慢理解


    -- Programming in Lua Coroutine(协程)
    --[[
    coroutine.create
    coroutine.resume
    coroutine.running
    coroutine.status
    coroutine.wrap
    coroutine.yield
    --]]

    --管道和过滤

    --生产者与用户的例子

    --[[
    ************************************************
    函数 :send
    用途 :暂停线程
    参数 :发送给下一次恢复的线程的数据
    返回值:无
    ************************************************
    --]]
    function send(x)
    coroutine.yield(x)
    end

    --[[
    ************************************************
    函数 :receive
    用途 :从线程中检索数据
    参数 :(function)需要被检索的线程
    返回值:(object)从上次暂停的线程中获取的数据
    ************************************************
    --]]
    function receive(co)
    local status, value = coroutine.resume(co)
    return value
    end

    --[[
    ************************************************
    函数:producer
    功能:不断生产值的函数(即生产者)
    参数:无
    返回值:线程
    ************************************************
    --]]
    function producer()
    return coroutine.create(
    function()
    while true do
    local x = io.read()
    --print(x)
    send(x)
    end
    end)
    end

    --[[
    ************************************************
    函数:fitler
    功能:改造由producer产生的值(即加工器)
    参数:线程(生产者)
    返回值:线程(经过加工的线程)
    ************************************************
    --]]
    function fitler(co)
    return coroutine.create(function()
    --math.huge是个无穷大的数
    for line=1, math.huge do
    local x = receive(co)
    --被加工后的数据
    x = string.format("%5d %s",line, x)
    send(x)
    end
    end)
    end


    --[[
    ************************************************
    函数:consumer
    功能:不断检索值的函数(用户)
    参数:线程(生产者)
    返回值:无
    ************************************************
    --]]
    function consumer(co)
    while true do
    local x = receive(co)
    --print(x)
    io.write(x, " ")
    end
    end

    --流程:生产》加工》用户使用
    --生产
    p = producer()
    --加工
    f = fitler(p)
    --用户使用
    consumer(f)

  • 相关阅读:
    Failed to load resource: the server responded with a status of 404 (Not Found) favicon.ico文件找不到
    合并排序
    python爬虫入门笔记--爬取垃圾分类查询【还有待改善】
    快速排序、合并排序和分治策略的基本思想
    动态规划的基本要素
    【转载】算法时间复杂度分析方法
    python爬虫入门笔记--知乎发现(爬取失败了)
    管理主界面的两个刷新操作
    把Excel选手名单信息导入到评委计分软件Access数据库的步骤
    评委打分回避功能的详细操作步骤
  • 原文地址:https://www.cnblogs.com/imzhstar/p/3607199.html
Copyright © 2011-2022 走看看