Lua一次执行几项任务

时间:2014-11-19 15:11:28

标签: multithreading lua coroutine

我一直在寻找一种同时执行多项任务(至少2)的解决方案。我在lua找到了像coroutines这样的东西。任何人都可以详细说明如何处理2个或多个任务吗?基本上我要做的是运行执行某些事件并使用lua脚本测量该进程的内存消耗。任何快速的解决方案或想法将受到高度赞赏。 感谢

2 个答案:

答案 0 :(得分:1)

看看io.popen(prog [, mode])

the documentation for io.popen,它"在另一个进程中启动程序"。

以下是我将如何实现这一点:

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

答案 1 :(得分:1)

我不知道这是否有帮助:

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