[Tutor] Threading in Python
Tim Peters
tutor@python.org
Fri, 22 Mar 2002 02:19:05 -0500
[STAN]
> How is it possible to run a seperate process in the background
> using Python ?
Sounds like you actually want a thread (!= process), and actually don't mean
much of anything by "background" <wink>.
> I have a main process that is console based, that gives the user
> a few options and acts according to their choice.
>
> But I want a process to be running in the background, which
> sleeps for x secs and keeps checking for some data [ Contacts a
> C++ extension].
>
> I tried thread.start_new_thread(...) and also the Thread class
> but was unsuccessful :
The good news is that this is easy to fix.
> This is what I tried ( a very simple and abstract simulation of
> what I intend to do)::
>
> *****************************************************
> from threading import *
> from random import Random
You're missing an "import time" here.
> def printResult():
> r = Random(68)
> while 1:
> time.sleep(0.5) # Is there a wait method I can
> # use here for more efficiency ?
What do you want it to wait *for*? Not enough information. Sleeping is
very efficient, btw, if the best answer you've got is "wait for half a
second".
> x = r.random()
> if (x > 0.75):
The parentheses aren't needed here, and are rarely seen in Python.
> print "The Event has occured"
>
> # End of printResult()
>
>
> def startit():
> t = Thread(target = printResult(),args=())
^^
The parentheses there are the cause of your problem: you're *calling*
printResult here, and since printResult() never returns, neither does the
call to Thread (your main thread never gets beyond this line). Delete the
parentheses and you'll be much happier.
> t.start()
> while 1:
> ch = raw_input("Continue ?")
> if (ch not in ('y',)):
> break
>
> # End of startit()
>
> >>> startit()
> ...
> I wanted printResult to be running in the background ..... But it
> is the only one that is running !!!
That's explained above -- your main thread is waiting for the printResult()
call to return; you never actually got so far as to create a second thread.
But you're close: remove the parens and you'll have two threads.