is Python fully object oriented ?

Martijn Faassen m.faassen at vet.uu.nl
Tue Jan 16 05:19:09 EST 2001


Delaney, Timothy <tdelaney at avaya.com> wrote:
> 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.

Right, at least the one I mentioned at the bottom, which is assigning back
to the immutable (or treated-as-immutable) attribute in the end. The
local variable technique in general doesn't seem to make matters much
worse by itself, except if other threads are expected to assign to 
a variable. 

> 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.
[snip example]

Right, I am aware of this problem, even though I lack lots of experience
dealing with it myself; I just wondered how it applied in particular to
the local variable trick. Your example shows that not using a local variable
has the same problem if object attributes are accessed at all. 

> Your situation is similar. You are getting a value, doing things with it,
> then setting the original value to it.

Right, this is the problem case.

> 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 is another reasonably safe way, which is Zope's way (after all, that's
where treating attributes as immutable is required if you want the 
persistent, and Zope's multithreaded); keep separate copies of the data
for each thread, and try to deal with conflicts as soon as the data is
writte to the object database. It seems to work fairly well; at least I
haven't experienced any significant problems with it yet.

> 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.

Oh, I realize that, I just wanted to know a little more detail about what
exactly you meant; I've done some research, just have minimal experience
with it in actual programs I wrote.

Thanks for your explanation!

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list