On Thu, Mar 5, 2009 at 9:07 AM, Chris Miles <[email protected]> wrote:
>
>
> On 05/03/2009, at 6:53 PM, Kamil Gorlo wrote:
>> I want to start another thread T1 in my Pylons App (manually, not
>> Paste#http worker) and have some global dict which all http workers
>> will read. But T1 periodically will update this dictionary (in fact
>> all he want to do is to swap this global dict with local dict which
>> was prepared during his work). In this dict I will have Python
>> primitives (other dicts too) and simple classes which act only as
>> 'structs'. Do I need lock?
>
> If unsure I'd suggest use a lock. What are you saving by skipping the
> lock? If the dict swap happens infrequently then the lock will be
> insignificant.
I will probably use lock, but even if this will be own implemented
RWLock (because there is no ReadWriteLock in python library) readers
also have to acquire it, not only writer thread. I was asking because
I want to know what can I assume using python primitives in
multithread environment and it looks that nobody knows for sure, what
is quite strange.
Hovewer, first tests shows on my ubuntu machine with python 2.5 that
using lock sometimes is faster than not using it. Could anybody
explain this?
This is simple example showing that x += 1 is not atomic:
>>> test1.py
import threading
gv = 0
class T(threading.Thread):
def run(self):
global gv
for i in xrange(10000000):
gv += 1
x = T()
y = T()
x.start()
y.start()
x.join()
y.join()
print gv
<<< test1.py
This is another example, but this time with lock:
>>> test2.py
import threading
gv = 0
gl = threading.Lock()
class T(threading.Thread):
def __init__(self, lock):
threading.Thread.__init__(self)
self.lock = lock
def run(self):
global gv
self.lock.acquire()
try:
for i in xrange(10000000):
gv += 1
finally:
self.lock.release()
x = T(gl)
y = T(gl)
x.start()
y.start()
x.join()
y.join()
print gv
<<< test2.py
And here are my results:
$ time python test1.py
14224533
real 0m6.630s
user 0m5.616s
sys 0m2.560s
$ time python test2.py
20000000
real 0m4.446s
user 0m4.380s
sys 0m0.036s
Cheers,
Kamil
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/pylons-discuss?hl=en
-~----------~----~----~----~------~----~------~--~---