[Zope-dev] thread safety in external methods
Jim Fulton
jim@digicool.com
Thu, 02 Sep 1999 09:06:44 -0400
Robin Becker wrote:
>
> How do I do thread safety inside an External method.
>
> I want to access a global singleton as
>
> def __ZGA():
> if not hasattr(sys.modules['__main__'],'__ZGA'):
> #unsafe here...
> Z=ZGA_calculator()
> # initialise things to do with Z
> sys.modules['__main__'].__dict__['__ZGA']=Z
> return sys.modules['__main__'].__dict__['__ZGA']
>
> the problem is controlling access to sys.modules['__main__'].__dict__['__ZGA']. I can't have a
> global lock inside my external method as I get a different environment with each call (which is
> why I need the singleton in the first place).
>
> It would be sufficient for my purposes if I could guarantee to get certain code run just once
> at startup time.
Is this actually necessary? Is it cirtical that only one ZGA_calculator
gets created? If not, you don't really have a thread-safety problem
here. If it is, then you could protect the section above with a lock:
import thread
zgalock=tread.allocate_lock()
def __ZGA():
zgaloc.acquire()
try:
if not hasattr(sys.modules['__main__'],'__ZGA'):
#unsafe here...
Z=ZGA_calculator()
# initialise things to do with Z
sys.modules['__main__'].__dict__['__ZGA']=Z
return sys.modules['__main__'].__dict__['__ZGA']
finally: zgaloc.release()
> Do I have to make a product or is there some easier way to do this.
I think that a product would be easier. With a product, you could
simply put the above code in the product __init__ module.
BTW, why do you want to hack __main__?
Jim
--
Jim Fulton mailto:jim@digicool.com Python Powered!
Technical Director (888) 344-4332 http://www.python.org
Digital Creations http://www.digicool.com http://www.zope.org
Under US Code Title 47, Sec.227(b)(1)(C), Sec.227(a)(2)(B) This email
address may not be added to any commercial mail list with out my
permission. Violation of my privacy with advertising or SPAM will
result in a suit for a MINIMUM of $500 damages/incident, $1500 for
repeats.