Thread Question
Felipe Almeida Lessa
felipe.lessa at gmail.com
Tue Feb 28 15:34:05 EST 2006
Em Ter, 2006-02-28 às 20:24 +0000, Grant Edwards escreveu:
> > I have seen examples that used classes, and other examples
> > that just called one thread start command - when should you
> > use one over another?
>
> I'm not sure what you mean by "use classes" vs. "calling a
> thread start command". My example above uses a class
> (threading.Thread) to create a thread object, and then calls
> its start method.
# He meant calling direct vs. subclassing. In your example you called
the Thread class directly, but you could have subclassed it.
# In your case, Edwards, I'd prefer subclassing because then you could
put some states in the class. A (bad) example:
class Foo(Thread):
def __init__(self):
Thread.__init__(self)
self.alive = False
self.running = True
def run(self):
while self.running:
self.alive = ping('myhost')
sleep(10)
def stop(self):
self.running = False
# Then you could:
a = Foo()
do_something()
print a.alive
do_something_more()
print a.alive
finish_everything()
print a.alive
a.stop()
# quit
--
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."
-- Sun Tzu, em "A arte da guerra"
More information about the Python-list
mailing list