[Python-Dev] A few lessons from the tempfile.py rewrite
Martin Sjögren
md9ms@mdstud.chalmers.se
17 Aug 2002 08:57:14 +0200
lör 2002-08-17 klockan 00.30 skrev Zack Weinberg:
> 2) pthread_once equivalent.
>
> pthread_once is a handy function in the C pthreads library which
> can be used to guarantee that some data object is initialized exactly
> once, and no thread sees it in a partially initialized state. I had
> to implement a fake version in tempfile.py.
>
> | _once_lock = _allocate_lock()
> |
> | def _once(var, initializer):
> | """Wrapper to execute an initialization operation just once,
> | even if multiple threads reach the same point at the same time.
> |
> | var is the name (as a string) of the variable to be entered into
> | the current global namespace.
> |
> | initializer is a callable which will return the appropriate initial
> | value for variable. It will be called only if variable is not
> | present in the global namespace, or its current value is None.
> |
> | Do not call _once from inside an initializer routine, it will deadl=
ock.
> | """
> |
> | vars = globals()
> | # Check first outside the lock.
> | if vars.get(var) is not None:
> | return
Wouldn't it make more sense to use has_key (or 'in')? If var is assigned
to None before _once is called, that value is overridden...
> | try:
> | _once_lock.acquire()
> | # Check again inside the lock.
> | if vars.get(var) is not None:
> | return
> | vars[var] = initializer()
> | finally:
> | _once_lock.release()
I agree that pthread_once is useful, and it would be nice to have
something like this in the standard library.
Regards,
Martin