[Tutor] Good threading tutorial
Gregor Lingl
glingl at aon.at
Wed Mar 31 16:18:32 EST 2004
Shawhan, Doug (EM, ITS) schrieb:
>How about a nice "hello threads" example? :-)
>
>-
>
I use this as a "hello threads" example in my classes:
#### EXAMPLE:
from threading import Thread
from random import random
from time import sleep
# COMPARE THE OUTPUT OF REPEATED RUNS OF THIS PROGRAM
def drop(char):
for i in range(10):
t = 0.5 * random()
sleep(t)
print char,
thr1 = Thread(target=drop, args=("+",))
thr2 = Thread(target=drop, args=("-",))
thr1.start()
thr2.start()
drop(":")
sleep(3.0) # comment out this line, run the program repeatedly
# and see what happens now
#### END OF EXAMPLE
Alas, it doesn't show what one needs to program with threads.
Id' prefer to have implementations of some classic examples
as for instance the producer consumer problem.
(Don't know if one could find some in the Python Docs)
TIM PETERS pointed someone (that was me) to his implementation
of the "dining philosophers problem" (from May 2000).
http://aspn.activestate.com/ASPN/Mail/Message/249937
If you know how beautiful and readable Tim's code uses to be,
you can't avoid reading it. (I don't *know* if it is still "state of
the art" with
Python 2.3. but I'd expect yes.)
To see how it works I recommend to run it with less than 1000
philosophers. ;-)
Regards, Gregor
P.S. Under windows: It doesn't run properly from IDLE - I think because
Tkinter is not "thread safe". On my machine in one test-run it even
killed IDLE.
More information about the Tutor
mailing list