Tuesday, July 17, 2007

Unending loops and the magic of threads.

Many months ago, I started this blog with a test post using the simplest possible template that I could find with blogger, hoping that Crunchy would be able to handle it. Alas, that was not the case.

Now that Crunchy can handle this blog (and much more), it is perhaps time to start again with a small but non-trivial example that illustrates some aspect of threads and infinite loops. I'm assuming you are viewing this blog using Crunchy, otherwise what I will be describing will simply not work.

Imagine you have a simple program such as the following:

>>> import time
>>> a = 1
... while a == 1:
... print "-",
... time.sleep(1)

How long will it take before this program ends? The answer is, of course, never. Such a program includes an infinite loop. Try typing it in the above interpreter to see it in action.

Crunchy is running this program in a separate thread, which allows you to continue using Crunchy while the program is running. Furthermore, the "Borg interpreter" used by Crunchy above has been designed so as to share its state with all other such interpreter (hence the name "Borg"). To see this, try using the interpreter below, running in a separate thread, to change the value of a.

>>> a = 0

If it does not work the first time (you may be getting a syntax error with Crunchy 0.9x), try it again. Eventually, it will allow you to break out of the seemingly infinite loop above.
Update: When you enter "a=0" the first time, the syntax error that it gives is due to the fact that the Borg interpreter is taking input assuming that you are still in the body of the while loop - therefore, it expects the code to be indented. If you write "a=0" in the second interpreter with the same indentation as you used in the original loop, you will see that you get Python's continuation prompt (...). Press "enter" a second time and you will get out of the loop; you may have to wait a few seconds to see the result.

An alternative to avoid the syntax error is to enter "break" in the second interpreter, with the same indentation as used in the loop, and pressing "enter" a second time. Then you can proceed with typing "a=0" in that second interpreter and everything will be fine.

Note: do not simply press "enter" first in the second interpreter, thinking that this will break out of the loop: it won't. In fact, this will result in the second interpreter being stuck in the loop. The only way out will be to reload the page and start from the beginning.