对lua协程的一点理解

读《Programming In Lua》协程那一章,比较困惑的还是procuer-consumer那个例子:

function consumer(prod)while true dolocal x = receive(prod)print(x)end
endfunction receive(prod)local status, value = coroutine.resume(prod)return value
endfunction send(x)coroutine.yield(x) -- go back to where resumed
endfunction producer()return coroutine.create(function()while true dolocal x = io.read()send(x)endend)
end-- consumer-driven design
consumer(producer())

producer产生数据,consumer消费数据,producer与consumer都在各自的协程中完成, 代码很短,但是很难读 - 至少不是那么一目了然,尤其比起这个直接的循环:

function produce()return io.read()
endfunction consume(x)print(x)
endwhile true dolocal x = produce()consume(x)
end

好在哪里?

书中说可以添加缓存控制速度,或者进行数据过滤 - 但是这在循环版本的producer-consumer中也都能做到,无非在在实现produce是多些逻辑,或者再加个filter的函数处理produce的返回值,协程版本毫无优势可言。

实在要说其优点,恐怕只是:producer和consumer的代码在各自的协程中实现,并通过resume-yield交换数据 - 实现了松耦合。这是个优点,可以还是不太满意,再往下看时,看到了全排列那个例子,稍作修改,让我比较直观的感觉到了协程这种控制结构的灵活性:

function send(a)coroutine.yield(a)
endfunction receive(prod)local status, value = coroutine.resume(prod)return value
endfunction consumer(prod)local function print_result(a)for _, v in ipairs(a) doio.write(v, " ")endio.write('\n')endwhile true dolocal a = receive(prod)if not a then break endprint_result(a)end
endfunction producer(a)function permgen(a, n)if n == 0 thensend(a) -- send something for consuming from an recursive callelsefor i=1, n doa[n], a[i] = a[i], a[n]permgen(a, n-1)a[n], a[i] = a[i], a[n]endendendlocal n = table.getn(a)return coroutine.create(function() permgen(a, n) end)
endconsumer(producer({1,2,3,4}))

这里全排列采用了递归算法:对数组中的每个元素,把它交换到数组末尾,然后对前n-1个元素的子数组做同样的事,当n==0时,输出一个排列。

这个在produce的时候,因为在一个递归调用中,你无法一个个返回:

  • 要么每找到一个,直接在里面处理 - 这样produce-consume的结构就有点混淆在一起;
  • 或者先把结果保存在一个共享内存中,产生全部排列后,再逐个处理 - 这样要另外开辟空间,流程上感觉也不够简洁。

于是,协程的有点就显现出来了,不同于简单函数中的return,协程可以在找到一个排列后,yield挂起本协程并返回该排列,返回到原来resume这个协程的代码处,取得数据进行consume,然后继续resume进入协程获取排列 - 通过协程灵活控制流程并传递数据,十分漂亮。

所以,那个循环版本的问题是:并不是所有produce的数据,都可以简单的return回来的。

转载于:https://www.cnblogs.com/baiyanhuang/archive/2012/11/17/2775315.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/274500.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

b端 ux 设计思维_借助系统思维从视觉设计过渡到UX

b端 ux 设计思维“How can I switch to UX?” This is a common question from visual designers because there’s a lot of overlap on the surface. But it can also be a difficult transition since UX encompasses much more below the surface.“如何切换到UX&#xff…

三面面试官:运行 npm run xxx 的时候发生了什么?

大家好,我是若川。近期发现好些小伙伴工作有2-3年了,基本不会写脚手架,或者说没学过脚手架。对脚手架大致是如何执行的基本不太知道。其实这类学习资料真的挺多的。而且我们基本天天 npm run dev,应该学习内部实现。不知道的小伙伴…

figma下载_Figma的自动版式实用

figma下载Figma’s Auto Layout has been around for a while, but not everyone’s aware of the benefits it brings. It doesn’t replace constraints, they’re still very much needed. The trick is to use the right feature where necessary. I want to show you how …

Qt通过ODBC读取excel文件

之前替学校考试科用C Builder做过一个小的数据库工具,处理excel表格用的,现在想转换到Qt平台下来,在网上搜了搜有一些利用OBDC读取xls文件的教程: http://hi.baidu.com/kxw102/item/770c496d5736470ca0cf0f1d http://blog.sina.co…

真 · 三面面试官:运行 npm run xxx 的时候发生了什么?

昨晚没权限我只放了链接,今天联系开了白名单。昨天推文主要是为了投票,表明 Node.js 的重要性,有人评论是水文。今天重新转载下。欢迎继续点此去投票。投票显示有高达近80% 表示不太会开发脚手架,看来大多数人确实没有应用场景。可…

ovo svm_反思我在OVO担任远程产品设计实习生的时间

ovo svmIn a quiet bedroom accompanied only by the low humming of my laptop fan, I sat before a Google Hangouts meeting, and got to know my colleagues for the first time, unaware of the joy of a ride that was waiting for me at OVO Design.在一个安静的卧室里&…

native的Socket向Android的LocalSocketServer发送汉字乱码的问题

native的Socket发送字节流默认是GB2312的,所以在Java方面需要指定GB2312 byte[] buffer new byte[50]; StringBuffer strBuf new StringBuffer(); InputStream input receiver.getInputStream(); while((len input.read(buffer)) ! -1) {String newStr new Str…

最受读者喜爱的前端书 Top 15【留言送书】

最受读者喜爱的前端书Top 15JavaScript高级程序设计(第4版)| 中文版累计销量32万册,JavaScript“红宝书”全新升级 | 涵盖ECMAScript 2019,全面深入,入门和进阶俱佳 | 结合视频讲解配套编程环境,助你轻松掌…

图文结合简单易学的 npm 包的发布流程

大家好,我是若川。我持续组织了近一年的源码共读活动,感兴趣的可以 点此扫码加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步。同时极力推荐订阅我写的《学习源码整体架构系列》 包含20余篇源码文章。历史面试…

拟态防御_拟态从未消失。 这就是为什么。

拟态防御Looking back on design languages, what Apple’s WWDC 2020 Keynote means for the future of design languages, and how we move on from here.回顾设计语言,Apple的WWDC 2020主题演讲对设计语言的未来意味着什么,以及我们如何从这里继续前进…

C++二维数组做形参

二位数组作为形参,目前仅知道两种形式,一种直接采用二维数组,一种是用二维指针。以下是做的一个简单的实例。 大家帮我看看,在实际应用中两者有和优缺点。当然,有更好的方式更好了。 以下均应用在字符串数组中 void ar…

经常开发后台管理系统,如何提升自己?推荐~【留言送书】

大家好,我是若川。之前送过N次书,可以点此查看回馈粉丝,现在又和博文视点合作再次争取了几本书,具体送书规则看文末。Vue.js是一套用于构建用户界面的渐进式框架。与其他大型框架不同的是,它可以自底向上逐层应用。Vue…

lottie 动画_使用After Effects和Lottie制作网络动画而不会损失质量

lottie 动画A quick getting started guide快速入门指南 I recently took on a project where the team wanted to add some animated icons and a logo. Besides UX & UI design I am also a motion graphic designer so I took on the challenge of doing it with after…

如何编辑ttf字体文件

libfreetype的目标是以最小的内存最快的速度,读取和渲染字体。因此libfreetype并不适宜用来编辑ttf字体文件。编辑字体文件,可以用FontCreator、微软fonttools、fontforge(苹果有个osxfonttools,这里不讨论)FontCreato…

最优秀的技术能力,是技术领导力!

最近和几个刚晋升为技术经理的朋友们约饭,席间互相吐槽职场中的喜怒哀乐: “开始带团队,既担心自己长时间不写代码技术功底退化,又怕手下人干不好,该怎么办?”“我都想回去敲代码了,拼命熬到管理…

模式匹配 怎么匹配减号_如何使您的应用导航与用户的思维模式匹配

模式匹配 怎么匹配减号One of the most interesting things about complex apps is that the navigation itself can be designed to support users’ mental model of the entire experience, thereby increasing engagement and decreasing potential user frustration.复杂应…

ux的重要性_颜色在UX中的重要性

ux的重要性When coming up with a new digital solution (desktop, mobile, app, whatever it may be) or any design concept, choosing the right colour palette is a crucial step that affects its success and outcome. The content, animations, copy and features may …

都2022 年了,你总不能还只会 npm i 吧?

大家好,我是若川。我持续组织了近一年的源码共读活动,感兴趣的可以 点此扫码加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步。同时极力推荐订阅我写的《学习源码整体架构系列》 包含20余篇源码文章。历史面试…

matlab学习:图像频域分析之Gabor滤波

很多同学需要源文档,所以添加了下载链接,方便大家共同学习进步~ 本文下载链接:http://files.cnblogs.com/yingying0907/Gabor%E7%AC%94%E8%AE%B0.zip Gabor变换是D.Gabor 1946年提出的。为了由信号的Fourier变换提取局部信息,引入…

云谦:前端框架的趋势与实践

大家好,我是若川。我持续组织了近一年的源码共读活动,感兴趣的可以 点此扫码加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步。同时极力推荐订阅我写的《学习源码整体架构系列》 包含20余篇源码文章。历史面试…