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

How does multishell exacly work?

Started by Creator, 03 March 2015 - 07:26 PM
Creator #1
Posted 03 March 2015 - 08:26 PM
Hi guys,

I'm working on an OS at the moment (just for coding practice and more in depth understanding of lua) and I came to the multitasking part. I looked at the multishell files and I do not totally understand how multishell works.

1st: How does it know it has to change the tab even if the function is not yielding?

2nd: How does it work in general?

You can look at the OS if you want ( you can find it here : TheOS) and give suggestions. Any constructive comment is welcome!

~Creator

PS: I googled about coroutines before asking but still don't totally get it. Moreover it feels like cheating if I used the Computercraft standart Multishell.
Edited on 03 March 2015 - 07:27 PM
CrazedProgrammer #2
Posted 03 March 2015 - 10:41 PM
You can use coroutines to pause and resume functions.
You can not run two functions at the same time but you can swap very quickly using coroutines.
What os.pullEvent does is calling coroutine.yield in the program function and handling events in the CraftOS function.
This also updates the multishell.
If a program doesn't call os.pullEvent or read() for too long it will cause an error.
This is not handled by lua but by java since lua can't run two functions at the same time.
Edited on 03 March 2015 - 10:43 PM
Bomb Bloke #3
Posted 03 March 2015 - 11:46 PM
Multishell runs the code for each tab in its own coroutine. Any events multishell picks up on, it passes on to those coroutines (though events related to user input specifically only go to the tab in focus).

If the code in a tab isn't yielding, multishell quite simply can't change tabs. But the event where you asked it to do so still goes into the queue, and so as soon as it gets the chance to check the queue contents for itself it can go ahead and do the switch.

Most scripts yield at a very rapid pace, so you're unlikely to notice the delay while multishell waits to regain control. ComputerCraft will in fact kill any process that runs for more than ten seconds without a yield. This is because you can only run one coroutine at a time per world - if one computer is doing something, no other system (computer, turtle, whatever) can do anything until it yields. Each instance of CraftOS running on a given system is just another coroutine running in the one Lua VM.

Lots of functions call os.pullEvent() indirectly. For example, you're yielding if you call read(), because that needs to pull char & key events. Likewise with sleep(), which needs to pull a timer event. As a general rule, if you're calling any function that has to "wait" for something, odds are you're yielding.