This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
oxygencraft's profile picture

How do i let more then 1 code block run at the same time?

Started by oxygencraft, 10 December 2015 - 04:02 AM
oxygencraft #1
Posted 10 December 2015 - 05:02 AM
What I am trying to do is make a server computer have some shutdown, reboot, change password etc AND process client requests at the same time. I don't want to have a computer just process the requests and the server option are on the client. If the server options are on the client then it could of been a security risk.
Mura #2
Posted 10 December 2015 - 05:19 AM
I think this: http://www.computercraft.info/wiki/Parallel.waitForAny will allow you to run two functions in parallel (I think its multiple threads… not sure)
Creator #3
Posted 10 December 2015 - 05:34 AM
There is no true parallel in Lua, there is more like a so fast you think it is in parallel, so using coroutines would not be a good improvement here.
Bomb Bloke #4
Posted 10 December 2015 - 05:38 AM
That depends entirely on which functions are being used within the separate "code blocks".

Though I do suspect that a generic event-catching loop would be the way to go, eg:

while true do
  local myEvent = {os.pullEvent()}

  if <event indicates shutdown request> then
    -- do stuff

  elseif <event indicates reboot request> then
    -- do stuff

  elseif <event indicates client request> then
    -- do stuff

  elseif etc...
    ...

  end
end

But what if you want to pull more events within the "if" blocks - eg to sleep, or to use certain peripheral functions? How do you do that without "skipping" the events needed to branch into the other "if" blocks later?

parallel.waitForAny() makes that easy; just divide everything up into individual functions and pass the lot in:

local function handleShutdown()
  while true do
    local myEvent = {os.pullEvent()}

    if <event indicates shutdown request> then
      -- do stuff
    end
  end
end

local function handleReboot()
  while true do
    local myEvent = {os.pullEvent()}

    if <event indicates reboot request> then
      -- do stuff
    end
  end
end

local function handleClients()
  while true do
    local myEvent = {os.pullEvent()}

    if <event indicates client request> then
      -- do stuff
    end
  end
end

-- Etc

parallel.waitForAny(handleShutdown, handleReboot, handleClients)
Edited on 10 December 2015 - 05:04 AM