[Tutor] Changing instance attributes in different threads

Michael Lange klappnase at freenet.de
Tue Feb 7 11:17:25 CET 2006


On Mon, 06 Feb 2006 18:34:18 -0500
Kent Johnson <kent37 at tds.net> wrote:


> 
> It sounds like you have some attributes that you are using as flags to 
> allow one thread to control another. There are definitely some pitfalls 
> here. You probably want to use threading.Condition or Queue.Queue to 
> communicate between the threads. Can you give more details of what you 
> are trying to do?
> 

I have used a boolean to control access to a variable that is used by two threads,
as in this example:

thread 1 does:

    while self.locked:
        pass
    self.locked = 1
    if condition:
        self.name = 'bob'
    else:
        self.name = 'mike'
    self.locked = 0

thread 2 does:

    while self.locked:
        pass
    self.locked = 1
    n = self.name
    self.locked = 0
    if n == 'bob':
        <do something>
    else:
        <do something else>

I *thought* this would be safe, but now reading this thread I start to doubt.
Are there any pitfalls I overlooked in this technique?

Thanks

Michael




More information about the Tutor mailing list