[Zope] How to prevent concurrent access to the same object?

Oliver Bleutgen myzope@gmx.net
Tue, 12 Feb 2002 19:39:26 +0100


Alexei Ustyuzhaninov wrote:


> Well, of course I had to try your product before comment, sorry. 
> Probably zope kernel is designed in such way that it can use RLock to 
> synchronize its child processes.
> 
> But generally RLock is inappropriate for this purpose in python. Take a 
> look at this test for example:
> 
> 09:50:33 aleks@aiu:~/testRLock
> $ cat test.py
> import os
> import threading
> import time
> 
> lock=threading.RLock()
> if os.fork()==0:
>   # Child process
>   time.sleep(1)
>   lock.acquire()
>   print "Process",os.getpid(),": the child acquired the lock"
> else:
>   # Parent process
>   lock.acquire()
>   print "Process",os.getpid(),": the parent acquired the lock"
>   time.sleep(5)
> lock.release()
> print "Process",os.getpid(),"released the lock"
> 
> 09:52:46 aleks@aiu:~/testRLock
> $ python test.py
> Process 6164 : the parent acquired the lock
> Process 6165 : the child acquired the lock
> Process 6165 released the lock
> Process 6164 released the lock


Alexei, I'm by no means an expert, but are you sure that you can use
os.fork() for what you want to do?

This works for me (sorry for the wrapping)

import threading
import time

my_lock = threading.RLock()
def my_thread(my_time=5, id='', lock=0):
     if lock: my_lock.acquire()
     time.sleep(my_time)
     if lock: my_lock.release()
     print "%s thread is finished" % id

slow = 5
fast = 1
t1 = threading.Thread(target=my_thread,kwargs={'my_time':slow, 'id':'slow'})
t2 = threading.Thread(target=my_thread,kwargs={'my_time':fast, 'id':'fast'})
t1.start()
t2.start()

t1 = threading.Thread(target=my_thread,kwargs={'my_time':slow, 
'id':'slow_with_lock', 'lock':1})
t2 = threading.Thread(target=my_thread,kwargs={'my_time':fast, 
'id':'fast_with_lock', 'lock':1})
t1.start()
t2.start()

Result:

~/work/pythontests/threadtest > python mythreadtest.py

fast thread is finished
slow thread is finished
slow_with_lock thread is finished
fast_with_lock thread is finished