简体   繁体   English

在 lua 中制作线程系统

[英]Making a threading system in lua

So I have been working with coroutines for a little while and I'm sort of having trouble trying to make what I want.所以我一直在使用协同程序一段时间,但我在尝试制作我想要的东西时遇到了麻烦。 I want a class that I can access objectivley creating objects as tasks or processes.我想要一个可以访问 objectivley 的类,将对象创建为任务或进程。 I think showing you code would be irrelevant and its not what I want either.我认为向您展示代码无关紧要,也不是我想要的。 So I'm just going to show you how i want the functionality所以我只是要向你展示我想要的功能

local task1 = Tasker.newTask(function()
  while true do 
    print("task 1")
  end
end)

local task2 = Tasker.newTask(function()
  while true do 
    print("task 2")
  end
end)

task1:start()
task2:start()

This way I can run multiple tasks at once, I want to be able to add new tasks when ever during runtime.这样我可以一次运行多个任务,我希望能够在运行时随时添加新任务。 Also I would like a way to stop the tasks also for example:此外,我还想要一种停止任务的方法,例如:

task2:stop()

But I don't want the stop command to entirely delete the task instance, only stop the task itself so I can invoke但我不希望停止命令完全删除任务实例,只停止任务本身以便我可以调用

task2:start()

Then maybe I could use a command to delete it.那么也许我可以使用命令来删除它。

task2:delete()

This would be very helpful and thank you for help if you need more info please ask.这将非常有帮助,如果您需要更多信息,请询问您的帮助。 Also i posted this on my phone so there may be typos and formatting issues我也把这个贴在我的手机上,所以可能会有拼写错误和格式问题

Lua doesn't natively support operating system threads, ie preemptive multitasking. Lua 本身不支持操作系统线程,即抢占式多任务处理。

You can use coroutines to implement your own cooperative "threads", but each thread must relinquish control before another can do anything.您可以使用协程来实现您自己的协作“线程”,但是每个线程必须在另一个线程可以做任何事情之前放弃控制。

local task1 = Tasker.newTask(function()
  while true do 
    print("task 1")
    coroutine.yield()
  end
end)

local task2 = Tasker.newTask(function()
  while true do 
    print("task 2")
    coroutine.yield()
  end
end)

Your Tasker class must take the task function and wrap it in a coroutine, then take care of calling coroutine.resume on them.你的 Tasker 类必须接受任务函数并将它包装在一个协程中,然后照顾对它们调用coroutine.resume Operations like stop and start would set flags on the task that tell Tasker whether or not to resume that particular coroutine in the main loop.stopstart这样的操作会在任务上设置标志,告诉塔斯克是否在主循环中恢复那个特定的协程。

你可以通过 C 来做到这一点。你也许可以使用LuaLanes 和 Linda 对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM