Lua execute several tasks at once

2.3k Views Asked by At

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

2

There are 2 best solutions below

2
On BEST ANSWER

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:

-- launch the prog you want to measure. I assume it does not quit immediately.
-- lua will not block here: it does not wait for prog to exit.
io.popen('script-you-want-to-measure')

-- launch the second process to measure the first.
local measure = io.popen('measuring-process', 'r')

-- read all will block until the measure program exits
local measure_output = measure:read('*a')
f:close()

-- do what you want with the output
0
On

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