当前位置: 首页 > 编程笔记 >

Lua编程示例(八):生产者-消费者问题

郎德馨
2023-03-14
本文向大家介绍Lua编程示例(八):生产者-消费者问题,包括了Lua编程示例(八):生产者-消费者问题的使用技巧和注意事项,需要的朋友参考一下

这个问题是比较经典的啦,基本所有语言的多线程都会涉及到,但是没想到Lua的这个这么复杂 抓狂
  看了好长时间才算看明白,先上个逻辑图:

   开始时调用消费者,当消费者需要值时,再调用生产者生产值,生产者生产值后停止,直到消费者再次请求。设计为消费者驱动的设计。
   图画的不太好,可以先将Filter遮住,它是过滤器对两个程序之间传递的信息进行处理。去掉Filter逻辑就更清晰些了,就是两个“线程”(其实是两个协同程序)互相调用。resume回到yield处开始,支持嵌套,返回到栈顶的yield位置。yield是非阻塞的“线程同步”。这到有点像linux里的管道通信。


 

 function receive(prod)
 print("receive is called")
 local status,value = coroutine.resume(prod)
 return value
end

function send(x,prod)
 print("send is called")
 return coroutine.yield(x)
end

function producer()
 return coroutine.create(function ()
 print("producer is called")
 while true do
 print("producer run again")
  local x = io.read()
  send(x)
 end
 end)
end

function filter(prod)
 return coroutine.create(function ()
 for line = 1,1000 do
  print("enter fliter "..line)
  local x = receive(prod)
  print("receive in filter finished")
  x= string.format("%5d %s",line,x)
  send(x,prod)
 end
 end)
end

function consumer(prod)
 print("consumer is called")
 while true do
 print("consumer run again")
 local x = receive(prod)
 print("retrun customer")
 io.write(x,"\n")
 end
end

p = producer()
f=filter(p)
consumer(f)


运行结果:

consumer is called
consumer run again
receive is called
enter fliter 1
receive is called
producer is called
producer run again
fsy
send is called
receive in filter finished
send is called
retrun customer
  1 fsy
consumer run again
receive is called
enter fliter 2
receive is called
producer run again
gaga
send is called
receive in filter finished
send is called
retrun customer
  2 gaga
consumer run again
receive is called
enter fliter 3
receive is called
producer run again
......

 类似资料:
  • 所谓的生产者消费者模型就是 某个模块(函数)负责生产数据,这些数据由另一个模块来负责处理 一般生产者消费者模型包含三个部分 生产者、缓冲区、消费者 为什么生产者消费者模型要含三个部分?直接生产和消费不行么? 一个案例说明一切 生产者好比现实生活中的某个人 缓冲区好比现实生活中的邮箱 消费者好比现实生活中的邮递员 如果只有生产者和消费者, 那么相当于只有写信的人和邮递员,那么如果将来过去的邮递员离职

  • 我如何将电话限制在每5秒一次。注意:只能修改reallySlowApi。 编辑:我知道,但是如果Api变得更慢,它就不能解决问题。我需要使用的最佳方式。

  • 向Kafka推送100,000条消息 在使用者使用所有100,000条消息之前,使用Ctrl-C关闭zookeeper和kafka服务(这是通过在consumer方法中使用来模拟的)。 发现 在zookeeper和kafka服务被关闭后,消费者继续在控制台上写消息。 问题 我如何使消费者从上次消费的消息的索引+1继续。 向Kafka推送100,000条消息 在使用者使用所有100,000条消息之前

  • 我有两个线程的问题,似乎没有正确同步。我基本上有一个布尔值名为“已占用”。当没有线程启动时,它被设置为false。但是当一个线程启动时,线程集被占用是真的,我有一个类,它有线程(run),它们调用下面的函数。 这是一个模拟银行的示例,它接收一个金额(初始余额),然后随机执行取款和存款。我的教授提到了一些关于从取款线程到存款线程的信号?这是怎么回事?在提取线程中,它应该运行到余额为2低,并等待存款线

  • 本教程演示了如何发送和接收来自Spring Kafka的消息。 首先创建一个能够发送消息给Kafka主题的Spring Kafka Producer。 接下来,我们创建一个Spring Kafka Consumer,它可以收听发送给Kafka主题的消息。使用适当的键/值序列化器和解串器来配置它们。 最后用一个简单的Spring Boot应用程序演示应用程序。 下载并安装Apache Kafka 要

  • 生产者线程与消费者线程使用信号量同步 生产者线程与消费者线程使用信号量同步 源码/* * Copyright (c) 2006-2018, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2018-08-24 yangjie the f