[Tutor] The thread module

Kent Johnson kent_johnson at skillsoft.com
Sat Sep 4 20:29:56 CEST 2004


Bernard,

Thinking about threads can twist your brain in knots, but for simple uses 
its pretty easy. The threading module is simpler to use than thread. To 
start a new thread, create a Thread object passing a function to the 
constructor. Then call start() on the object. The thread will run until the 
function you pass it returns, or forever if the function doesn't return.

Here is a simple example of creating two threads that run forever, this is 
similar to what you are trying to do:
 >>> from threading import Thread
 >>> import time

Here are the two callback functions:
 >>> def f1():
...   while 1:
...     print 'f1'
...     time.sleep(1)
...
 >>> def f2():
...   while 1:
...     print 'f2'
...     time.sleep(3)
...

Create the two threads and start them. You don't have to do this in one 
line from your program but from the console it is easier...
 >>> Thread(target=f1).start(); Thread(target=f2).start()
f1
f2
 >>> f1
f1
f2
f1
f1
f1
f2
f1
f1
etc.

Another way you could write your program is to have one loop that checks to 
see if it is time to run any of the tasks. It could keep a list of 
scheduled tasks and check the list each time it wakes.

Kent

At 05:36 PM 9/4/2004 +0200, Bernard Lebel wrote:
>Hello,
>
>It is my first ever attempt at managing threads. And I must admit that I am
>absolutely lost! I don't know if I'm using the right approach at all for
>what I'm after, so if you have any suggestion, do not hesitate!
>
>What I'm looking for:
>I launch a command line shell, import a script, and the script runs forever.
>The watches two main things:
>1- The accessibility of two shared locations on the network, so if one of
>them goes down (or both), an email is sent to various people. When one
>server goes down, it is no longer checked. When both server go down, none
>are checked. A check is performed every 5 minutes.
>2- The remaining space on several network volumes, and if one goes under
>5Gb, again, an email is sent. The check is performed no matter what, every
>hour.
>
>Currently I have two scripts that do the job very well.
>
>Now the problem is that I want to consolidate them into one, so I don't have
>two python shell running, but one.
>I figured that using child threads would be a good way to manage this,
>because each thread could manage task. Basically I am looking at doing two
>parallel loops.
>
>
>So I've messed a little bit with the thread module, and have read the pdf
>tutorial from Norman Matloff, but I'm still confused about the whole thing.
>Anyone can recommend tutorial or ressources for this? Or even a different
>approach for the problem?
>
>
>Thanks in advance
>Bernard
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list