Lua使用协程实现生产者和消费者

function producer()
--定义生产的商品
	local i = 0;
	while i < 100
	do
		i = i + 1
		print("produce :"..i)
		--通过协程实现
		coroutine.yield(i)
	end
end
function consumer()
	while true
	do
		local status, result = coroutine.resume(po)
		print("consume:", result)
		if(result == 99) then break
		end
	end
end
--这里必须是producer而不能是producer()
po = coroutine.create(producer)
consumer()

为什么coroutine.create的时候传方法名而不能传produer()

在 Lua 中,函数名和函数调用是两个不同的概念。当你使用 coroutine.create(producer) 时,你将函数名 producer 传递给了 coroutine.create 函数。这表示你想要创建一个协程对象来运行名为 producer 的函数。

而当你使用 coroutine.create(producer()) 时,你实际上是在尝试调用函数 producer,并将函数的返回值作为参数传递给 coroutine.create 函数。这可能会导致一些问题,因为 producer 函数内部使用了 coroutine.yield 函数,因此它返回的实际上是一个协程对象,而不是一个值。

因此,当你使用 coroutine.create(producer()) 时,你会得到一个 "attempt to yield across metamethod/C-call boundary" 错误,因为你尝试从函数调用的边界内使用 yield 函数。

如果你要使用 coroutine.create 创建一个协程对象来运行 producer 函数,应该使用 coroutine.create(producer),而不是 coroutine.create(producer())

所以,将 po = coroutine.create(producer()) 改为 po = coroutine.create(producer) 即可解决这个问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生产者消费者模式是一种常见的多线程编程模式,可以用于解决生产者消费者之间的数据交换问题。在Java中,可以使用多种方式实现生产者消费者模式,比如使用wait()和notify()方法、使用BlockingQueue等。以下是一种使用wait()和notify()方法实现生产者消费者模式的示例代码: ``` public class ProducerConsumerExample { private static final int BUFFER_SIZE = 10; private static List<Integer> buffer = new ArrayList<>(BUFFER_SIZE); public static void main(String[] args) { Thread producerThread = new Thread(new Producer()); Thread consumerThread = new Thread(new Consumer()); producerThread.start(); consumerThread.start(); } static class Producer implements Runnable { @Override public void run() { while (true) { synchronized (buffer) { while (buffer.size() == BUFFER_SIZE) { try { buffer.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int item = (int) (Math.random() * 100); buffer.add(item); System.out.println("Produced item: " + item); buffer.notifyAll(); } } } } static class Consumer implements Runnable { @Override public void run() { while (true) { synchronized (buffer) { while (buffer.isEmpty()) { try { buffer.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int item = buffer.remove(0); System.out.println("Consumed item: " + item); buffer.notifyAll(); } } } } } ``` 在这个示例代码中,Producer和Consumer都是实现了Runnable接口的线程类。Producer线程不断地生成随机数,并将其添加到buffer中,如果buffer已满,则等待。Consumer线程不断地从buffer中取出数据,并打印出来,如果buffer为空,则等待。在每次修改buffer的时候,都需要获取buffer的锁,并在修改完成后调用notifyAll()方法来唤醒其他等待的线程。 至于"lua closure factory 完整代码"和"中文加密"的问题,我可以回答。但是请注意,这些问题的答案并不代表我是一个真正的AI,而只是一个由CSDN开发的模拟AI。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值