You are very close. Coroutines are cooperative threads, so the function you pass to process will have to call coroutine.yield (ideally, often). Also Process needs resume() so the "thread" can do more work. The coroutine can be stopped anytime from outside the coroutine while not executing the coroutine: just don't resume it, and nil it. It can be stopped anytime from within the coroutine by not yielding but returning. It would look something like this (not tested for bugs):
function Process:start()
self.thread = coroutine.create(self.func)
self:resume() -- run to next yield
end
function Process:resume()
coroutine.resume(self.thread)
end
function Process:stop() -- from "outside" thread
self.thread = nil
end
function Process:status()
return coroutine.status(self.thread)
end
Make sure you look at Lua ref manual sections 2.11 for example of how to structure your function using coroutine.yield, and section 5.2 for details on coroutine module.
You could have multiple threads:
function func1() ... end
function func2() ... end
p1 = newProcess("func1", func1)
p2 = newProcess("func2", func2)
p1:start() -- runs func1 to its first yield
p2:start() -- runs func2 to its first yield
p1:resume() -- runs func1 to its second yield
p2:resume() -- runs func2 to its second yield
Note that the above will not work if you have func1 as such:
function func1()
sleep(100) -- seconds
end
But it will work if func1 is this:
function func1()
for i=1,100 do
sleep(1)
coroutine.yield()
end
end
Both sleep the same amount of time (100 s) but the first version will return only after 100 s, whereas the second one can be called 100 times, which gives the same results as single core multiple threads. Note: sleep is pseudocode, it is not available in Lua; and sleep is only used to illustrate a function that takes a large amount of time to do something that can broken down into many little chunks.