电脑工艺中的多线程函数

我正在进行一个项目,想要更新屏幕上的时钟,每隔5秒钟刷新一次,除非用户输入。这是我目前的代码,

function thread1()
  term.clear()
  term.setCursorPos(1,1)
  write (" SteveCell        ")
  local time = os.time()
  local formatTime = textutils.formatTime(time, false)
  write (formatTime)
  print ("")
  print ("")
  for i=1,13 do
    write ("-")
  end
  print("")
  print ("1. Clock")
  print ("2. Calender")
  print ("3. Memo")
  print ("4. Shutdown")
  for i=1,13 do
    write ("-")
  end
  print ("")
  print ("")
  write ("Choose an option: ")
  local choice = io.read()
  local choiceValid = false
  if (choice == "1") then
    -- do this
  elseif (choice == "2") then
    -- do that
  elseif (choice == "3") then
    -- do this
  elseif (choice == "4") then
    shell.run("shutdown")
  else
    print ("Choice Invalid")
    os.sleep(2)
    shell.run("mainMenu")
  end
end

function thread2()
  local myTimer = os.startTimer(5)
  while true do
    local event,timerID = os.pullEvent("timer")
    if timerID == myTimer then break end
  end
  return
end

parallel.waitForAny(thread1, thread2)
shell.run("mainMenu")

很不幸,它没有起作用。如果有人能帮我解决这个问题,我将非常感激。谢谢 :)

点赞
用户3554071
用户3554071

你想要做类似这样的事情(我没有进行正确的屏幕绘制,只是时间)

local function thread1_2()
   -- 两个线程合在一起!

   while true do
      local ID_MAIN = os.startTimer(5)
      local ID = os.startTimer(0.05)
      local e = { os.pullEvent() }
      if e[1] == "char" then
         -- 检查这里所有带有变量 e [2] 的选项
         printstring.format(“已按下%s”,e[2]))
         打破--走出 'thread'
      elseif e[1] ==“timer”并且e [2] == ID then
         ID = os.startTimer(0.05) - 在cc中最短的间隔
         redrawTime() - 在此函数中重绘和更新时间!
      elseif e[1] ==“timer”并且e [2] == MAIN_ID then
         打破
      结束
   end
end

另外,在正确的[论坛](http://www.computercraft.info/forums2/index.php ?/forum/14-ask-a-pro/)中提问,那里有更多的机会得到答案!另一个注意事项是更深入地了解事件处理,这真的有帮助。

2014-10-17 13:44:03
用户4162169
用户4162169

FYI,Lua 并没有像同时执行多个例程的 'multi-threading'。它实现的是 'thread parking'。你可以在不同的例程之间进行切换 (yielding),然后再切换回来,它会从离开的地方继续执行,但是任何时候只有一个例程是活跃的。

这是我经常用来参考 Lua 的资料,在这里详细说明了: http://lua-users.org/wiki/CoroutinesTutorial

2014-10-20 16:30:32