简体   繁体   中英

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. 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.

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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