[Tutor] Threading a Class?

Remco Gerlich scarblac@pino.selwerd.nl
Mon, 9 Jul 2001 19:26:47 +0200


On  0, Britt Green <britt_green@hotmail.com> wrote:
> Alright, I think I have the basics of my Time class going the way I want it 
> to. Now I need to make it threaded. This is what I have so far:
> 
> import time
> 
> class GameTime:
>     def __init__(self):
>         print "Class GameTime initiated."
> 
>     def updateTime(self):
>         while 1:
>             self.theTime = time.ctime(time.time())
>             print self.theTime
>             time.sleep( 20 )
> 
> myTime = GameTime()
> myTime.updateTime()
> 
> The time.sleep() function causes my program to, well, sleep for twenty 
> seconds and during that time my program can do nothing else. I'd like to put 
> this in a thread so that other things can be executed while the timer is 
> sleeping.

import threading

mythread = threading.Thread(target=myTime.updateTime)
mythread.start()

Now mythread is running the updateTime function, and your program continues
in the main thread.

The thread won't stop by itself - it's in a while 1:. Change that into a
while someguard: so that you can set someguard to 0 from the main thread, if
you want to stop the thread.

> Unfortunately, I'm kind of stuck on how to do this. I've gotten pointed in 
> the right direction by a couple of books, but because this is the first time 
> I've written anything involving threads, I could really use some 
> step-by-step instruction on this.

This is the simple part; getting a thread to run. Concurrent programming
holds many gotchas though, it's not a trivial subject. Just to name a few
things: if you have a GUI, make sure only one thread works with GUI elements.
Also, if several threads want to change the same variable, you may have race
conditions. I.e, if x == 0, and two threads execute "x = x+1", it may go
like this:

thread 1               thread 2
get x
compute x+1 (=1)
                       get x
                       compute x+1 (=1)
store 1 in x
                       store 1 in x

Now x is 1 after both threads finish. But this is also possible:

thread 1               thread 2
get x
compute x+1 (=1)
store 1 in x
                       get x
                       compute x+1 (=2)
                       store 1 in x

Now x is 2.

You need to put a *semaphore* around x when you do something with it; it's a
sort of lock around the variable, saying "i'm busy with this now, wait until
I'm done before you start".

This space is too small to explain everything; just expect the
unexpected...

-- 
Remco Gerlich