is Python fully object oriented ?

Delaney, Timothy tdelaney at avaya.com
Mon Jan 15 18:10:11 EST 2001


Oh - avoiding this technique does not magically make the danger go away.
However, *using* this technique is an almost guaranteed sure-fire way to
stuff things up in a multi-threaded app.

The problem is, multiple threads can be executing the same bit of code at
the same time. This is a problem with *any* system which accesses shared
data - whether it be multi-threaded, multiple apps accessing the same file,
etc.

A classic example is:

class c:

	a = 1

	def f (self):
		c.a = 2
		c.a = c.a + 1
		return c.a

Now, if you have two threads running that both called f() on instances of c
(different or the same instances) they have multiple ways of executing.

Lets call these two threads A and B :)

A: c.a = 2
A: c.a = c.a + 1
A: return c.a (returns 3)
B: c.a = 2
B: c.a = c.a + 1
B: return c.a (returns 3)

In a non-threaded system, this is guaranteed.

Now, let's look at another execution order ...

A: c.a = 2
A: c.a = c.a + 1
B: c.a = 2
A: return c.a (returns 2)
B: c.a = c.a + 1
B: return c.a (returns 3)

This is a major problem.

Your situation is similar. You are getting a value, doing things with it,
then setting the original value to it. Meanwhile, a second thread has
grabbed *the original value*, does something else with it (i.e. not
necessarily in the same method, so does something different), then after
your first thread assigns it back, the *second* thread assigns it back. Your
first thread is now likely to become very confused very quickly.

The only safe way to do *exactly* what you are proposing is to treat it as a
"critical section" - i.e. use a mutex or some other mechanism to ensure that
only one thread is modifying that data at any time. This then gets rid of
all your performance gains of using a local variable as the critical section
becomes a bottleneck.

There are many techniques for making things "thread-safe" - if you are
interested I would suggest doing a bit of research. There's not way I can
explain it all here.

Tim Delaney
Avaya Australia
+61 2 9352 9079

> -----Original Message-----
> From: m.faassen at vet.uu.nl [mailto:m.faassen at vet.uu.nl]
> Sent: Monday, 15 January 2001 11:20 PM
> To: python-list at python.org
> Subject: Re: is Python fully object oriented ?
> 
> 
> Delaney, Timothy <tdelaney at avaya.com> wrote:
> [snip me describing how object attributes can be copied into local
>  variables]
> > Ooh - dangerous in a multithreaded app ... ;)
> 
> I have little experience programming multithreaded apps, but find it
> hard to believe that avoiding this techniques makes all the danger go
> away without the need for special attention anyway. Could you 
> elaborate?
> 
> Regards,
> 
> Martijn
> -- 
> History of the 20th Century: WW1, WW2, WW3?
> No, WWW -- Could we be going in the right direction?
> -- 
> http://www.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list