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

Help with creating a multitasking OS.

Started by mrdawgza, 04 April 2014 - 11:37 AM
mrdawgza #1
Posted 04 April 2014 - 01:37 PM
Yes I'm back again…….
However I am developing a new operating system to success my previous one.
The previous one is like one of the first Nokia phones made, simple…
The new one I'm developing will be able to multitask, like Windows..

I've spent quite some time messing around with the parallel API and it keeps messing up, which eventually made me stuff up the code (it's gone now).

So how can I make a proper multitasking environment?
apemanzilla #2
Posted 04 April 2014 - 01:53 PM
Step 1: Learn the basics of Lua coroutines. There are lots of online guides on this.
Step 2: If necessary (which it probably is) make a custom coroutine manager. Parallels is a good one, but it falls short in many places. Here is a very basic one that allows for adding new coroutines while the loop is still running - something you can't do with the parallel API.

coroutines = {}
function create(func, key)
  local key = key or table.maxn(coroutines)
  coroutines[key] = coroutine.create(func)
end

function loop()
  while true do
    --Count living coroutines
    local i = 0
    for k,v in pairs(coroutines) do
      if coroutine.status(v) ~= "dead" then i = i +1 end
    end
    --Break loop if there are no living coroutines
    if i < 1 then break end
    --Catch event data
    local eventData = {coroutine.yield()}
    --Send it to all the coroutines
    for k,v in pairs(coroutines) do
      pcall(coroutine.resume(v,unpack(eventData)))
      --Pcall to prevent errors if the coroutine can't resume, you'd probably want to have better detection than this
    end
  end
end
Step 3: Make on OS