Why not easy Thread synchronization?
Dave Brueck
dave at pythonapocrypha.com
Tue May 13 18:50:11 EDT 2003
On Tue, 13 May 2003, Iwan van der Kleyn wrote:
> It's very easy writing simple threaded programs in Python. In fact, its
> part of my "evangelize demo's" :-)
> However, thread synchroni(s/z)ation seems to be a bit more fussy and
> complex then, for example, Java.
I dunno - most of the time when I want synchronization it's not around a
single method but several, and in the Java model I always got confused
because the syntax made it look like synchronization occurred around a
method and not an entire object.
> Why not a "synchronization" reserved word like in Java which takes care
> of "scary" bits under the hood?
>
> For example:
>
> sync def log(s): #in which the hypothetical keyword 'sync' makes the
> function 'log' thread safe
> sys.stout.write(s)
> sys.stout.flush()
>
> Seems to be a bit more fitting to Python mucking about with locks and
> mutexes.
Couldn't you add something like that yourself (untested):
import threading
def MakeSynchronized(func):
def f(*args, **kwargs):
f.lock.acquire()
try:
return f.realfunc(*args, **kwargs)
finally:
f.lock.release()
f.lock = threading.Lock()
f.realfunc = func
return f
And then you could take any function and make it synchronized:
def Log(what):
sys.stdout.write(what)
sys.stdout.flush()
Log = MakeSynchronized(Log)
-Dave
More information about the Python-list
mailing list