【问题标题】:Lua execute several tasks at onceLua 一次执行多个任务
【发布时间】:2014-11-19 15:11:28
【问题描述】:

我一直在寻找同时执行多个任务(至少 2 个)的解决方案。我在 lua 中发现了类似协程的东西。任何人都可以详细说明如何处理 2 个或多个任务吗?基本上我要做的是运行执行一些事件并使用 lua 脚本测量该进程的内存消耗。任何快速的解决方案或想法将不胜感激。 谢谢

【问题讨论】:

  • lua 不是多线程的。协同程序不会在它们协同执行多任务的同时运行。如果你需要的话,你可以在后台运行一个进程。
  • 能否详细说明在后台运行进程?我正在寻找的是以下内容:启动第一个进程并立即启动第二个进程....它们中的任何一个是否在后台运行都没有关系

标签: multithreading lua coroutine


【解决方案1】:

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

the documentation for io.popen,它“在另一个进程中启动 prog”。

这是我将如何实现的:

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

【讨论】:

  • 感谢大家的回答...与此同时,我们找到了另一个解决方案,我们在 C++ 中启动线程,然后我们可以使用 Lua 脚本运行并发线程..
  • @Chhabilal,您能否提供一个指向您的解决方案的指针,以便其他人可以学习?
【解决方案2】:

我不知道这是否有帮助:

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

【讨论】:

    猜你喜欢
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2020-03-09
    • 1970-01-01
    • 2014-10-25
    • 2014-03-01
    相关资源
    最近更新 更多