I have been looking for a solution to execute several task (atleast 2) simultaneously. I found something like coroutines in lua. Can anybody please clarify me in detail how to handle 2 or more than one task? Basically what I am trying to do is to run execute some event and measure the memory consumption for that process using lua script. Any quick solution or ideas would be highly appreciated. Thanks
Lua execute several tasks at once
2.3k Views Asked by Chhabilal At
2
There are 2 best solutions below
0

I don't know if this can help:
-- task-like example --
local tasks = { } -- queue
local task = coroutine.wrap -- alias
local function suspend ( )
return coroutine.yield (true)
end
local function shift (xs)
return table.remove (xs, 1) -- removes the first element
end
local function push (xs, x)
return table.insert (xs, x) -- inserts in the last position
end
local function enqueue (f)
return push (tasks, task (f))
end
-- begin to run the tasks --
local function start ( )
local curr
while #tasks > 0 do -- while the tasks queue isn't empty
curr = shift (tasks)
if curr ( ) then push (tasks, curr) end -- enqueue the task if still alive
end
end
-- create a task and begin to run the tasks --
local function spawn (f)
local curr = task (f) --
if curr ( ) then push (tasks, curr) end
return start ( )
end
-- adds task to tasks queue --
enqueue (function ( )
for i = 1, 3 do
print ("Ping. <<", i)
-- os.execute "sleep 1" -- uncomment if you're using *nix
suspend( )
end
end)
-- yet another task --
enqueue (function ( )
for i = 1, 5 do
print "..."
suspend( )
end
end)
-- begins to run the tasks --
spawn (function ( )
for i = 1, 5 do
print ("Pong. >>", i)
-- os.execute "sleep 1" -- uncomment if you're using *nix
suspend( )
end
end)
-- end of script --
Take a look a
io.popen(prog [, mode])
.From the documentation for io.popen, it "starts prog in an other process".
Here is how I would implement this: