Get rid of all __private variables and methods in the threading module.

These have mostly just gotten in the way of legitimate unanticipated use.
This commit is contained in:
Guido van Rossum 2007-08-20 19:25:41 +00:00
parent 61e21b52f1
commit d06489945f

View File

@ -39,10 +39,10 @@ if __debug__:
def __init__(self, verbose=None):
if verbose is None:
verbose = _VERBOSE
self.__verbose = verbose
self._verbose = verbose
def _note(self, format, *args):
if self.__verbose:
if self._verbose:
format = format % args
format = "%s: %s\n" % (
currentThread().getName(), format)
@ -80,28 +80,28 @@ class _RLock(_Verbose):
def __init__(self, verbose=None):
_Verbose.__init__(self, verbose)
self.__block = _allocate_lock()
self.__owner = None
self.__count = 0
self._block = _allocate_lock()
self._owner = None
self._count = 0
def __repr__(self):
owner = self.__owner
owner = self._owner
return "<%s(%s, %d)>" % (
self.__class__.__name__,
owner and owner.getName(),
self.__count)
self._count)
def acquire(self, blocking=1):
me = currentThread()
if self.__owner is me:
self.__count = self.__count + 1
if self._owner is me:
self._count = self._count + 1
if __debug__:
self._note("%s.acquire(%s): recursive success", self, blocking)
return 1
rc = self.__block.acquire(blocking)
rc = self._block.acquire(blocking)
if rc:
self.__owner = me
self.__count = 1
self._owner = me
self._count = 1
if __debug__:
self._note("%s.acquire(%s): initial success", self, blocking)
else:
@ -112,12 +112,12 @@ class _RLock(_Verbose):
__enter__ = acquire
def release(self):
if self.__owner is not currentThread():
if self._owner is not currentThread():
raise RuntimeError("cannot release un-aquired lock")
self.__count = count = self.__count - 1
self._count = count = self._count - 1
if not count:
self.__owner = None
self.__block.release()
self._owner = None
self._block.release()
if __debug__:
self._note("%s.release(): final release", self)
else:
@ -130,23 +130,23 @@ class _RLock(_Verbose):
# Internal methods used by condition variables
def _acquire_restore(self, state):
self.__block.acquire()
self.__count, self.__owner = state
self._block.acquire()
self._count, self._owner = state
if __debug__:
self._note("%s._acquire_restore()", self)
def _release_save(self):
if __debug__:
self._note("%s._release_save()", self)
count = self.__count
self.__count = 0
owner = self.__owner
self.__owner = None
self.__block.release()
count = self._count
self._count = 0
owner = self._owner
self._owner = None
self._block.release()
return (count, owner)
def _is_owned(self):
return self.__owner is currentThread()
return self._owner is currentThread()
def Condition(*args, **kwargs):
@ -158,7 +158,7 @@ class _Condition(_Verbose):
_Verbose.__init__(self, verbose)
if lock is None:
lock = RLock()
self.__lock = lock
self._lock = lock
# Export the lock's acquire() and release() methods
self.acquire = lock.acquire
self.release = lock.release
@ -177,28 +177,28 @@ class _Condition(_Verbose):
self._is_owned = lock._is_owned
except AttributeError:
pass
self.__waiters = []
self._waiters = []
def __enter__(self):
return self.__lock.__enter__()
return self._lock.__enter__()
def __exit__(self, *args):
return self.__lock.__exit__(*args)
return self._lock.__exit__(*args)
def __repr__(self):
return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
def _release_save(self):
self.__lock.release() # No state to save
self._lock.release() # No state to save
def _acquire_restore(self, x):
self.__lock.acquire() # Ignore saved state
self._lock.acquire() # Ignore saved state
def _is_owned(self):
# Return True if lock is owned by currentThread.
# This method is called only if __lock doesn't have _is_owned().
if self.__lock.acquire(0):
self.__lock.release()
if self._lock.acquire(0):
self._lock.release()
return False
else:
return True
@ -208,7 +208,7 @@ class _Condition(_Verbose):
raise RuntimeError("cannot wait on un-aquired lock")
waiter = _allocate_lock()
waiter.acquire()
self.__waiters.append(waiter)
self._waiters.append(waiter)
saved_state = self._release_save()
try: # restore state no matter what (e.g., KeyboardInterrupt)
if timeout is None:
@ -236,7 +236,7 @@ class _Condition(_Verbose):
if __debug__:
self._note("%s.wait(%s): timed out", self, timeout)
try:
self.__waiters.remove(waiter)
self._waiters.remove(waiter)
except ValueError:
pass
else:
@ -248,7 +248,7 @@ class _Condition(_Verbose):
def notify(self, n=1):
if not self._is_owned():
raise RuntimeError("cannot notify on un-aquired lock")
__waiters = self.__waiters
__waiters = self._waiters
waiters = __waiters[:n]
if not waiters:
if __debug__:
@ -264,7 +264,7 @@ class _Condition(_Verbose):
pass
def notifyAll(self):
self.notify(len(self.__waiters))
self.notify(len(self._waiters))
def Semaphore(*args, **kwargs):
@ -278,38 +278,38 @@ class _Semaphore(_Verbose):
if value < 0:
raise ValueError("semaphore initial value must be >= 0")
_Verbose.__init__(self, verbose)
self.__cond = Condition(Lock())
self.__value = value
self._cond = Condition(Lock())
self._value = value
def acquire(self, blocking=1):
rc = False
self.__cond.acquire()
while self.__value == 0:
self._cond.acquire()
while self._value == 0:
if not blocking:
break
if __debug__:
self._note("%s.acquire(%s): blocked waiting, value=%s",
self, blocking, self.__value)
self.__cond.wait()
self, blocking, self._value)
self._cond.wait()
else:
self.__value = self.__value - 1
self._value = self._value - 1
if __debug__:
self._note("%s.acquire: success, value=%s",
self, self.__value)
self, self._value)
rc = True
self.__cond.release()
self._cond.release()
return rc
__enter__ = acquire
def release(self):
self.__cond.acquire()
self.__value = self.__value + 1
self._cond.acquire()
self._value = self._value + 1
if __debug__:
self._note("%s.release: success, value=%s",
self, self.__value)
self.__cond.notify()
self.__cond.release()
self, self._value)
self._cond.notify()
self._cond.release()
def __exit__(self, t, v, tb):
self.release()
@ -325,7 +325,7 @@ class _BoundedSemaphore(_Semaphore):
self._initial_value = value
def release(self):
if self._Semaphore__value >= self._initial_value:
if self._value >= self._initial_value:
raise ValueError, "Semaphore released too many times"
return _Semaphore.release(self)
@ -339,34 +339,34 @@ class _Event(_Verbose):
def __init__(self, verbose=None):
_Verbose.__init__(self, verbose)
self.__cond = Condition(Lock())
self.__flag = False
self._cond = Condition(Lock())
self._flag = False
def isSet(self):
return self.__flag
return self._flag
def set(self):
self.__cond.acquire()
self._cond.acquire()
try:
self.__flag = True
self.__cond.notifyAll()
self._flag = True
self._cond.notifyAll()
finally:
self.__cond.release()
self._cond.release()
def clear(self):
self.__cond.acquire()
self._cond.acquire()
try:
self.__flag = False
self._flag = False
finally:
self.__cond.release()
self._cond.release()
def wait(self, timeout=None):
self.__cond.acquire()
self._cond.acquire()
try:
if not self.__flag:
self.__cond.wait(timeout)
if not self._flag:
self._cond.wait(timeout)
finally:
self.__cond.release()
self._cond.release()
# Helper to generate new thread names
_counter = 0
@ -398,53 +398,53 @@ class Thread(_Verbose):
_Verbose.__init__(self, verbose)
if kwargs is None:
kwargs = {}
self.__target = target
self.__name = str(name or _newname())
self.__args = args
self.__kwargs = kwargs
self.__daemonic = self._set_daemon()
self.__started = False
self.__stopped = False
self.__block = Condition(Lock())
self.__initialized = True
self._target = target
self._name = str(name or _newname())
self._args = args
self._kwargs = kwargs
self._daemonic = self._set_daemon()
self._started = False
self._stopped = False
self._block = Condition(Lock())
self._initialized = True
# sys.stderr is not stored in the class like
# sys.exc_info since it can be changed between instances
self.__stderr = _sys.stderr
self._stderr = _sys.stderr
def _set_daemon(self):
# Overridden in _MainThread and _DummyThread
return currentThread().isDaemon()
def __repr__(self):
assert self.__initialized, "Thread.__init__() was not called"
assert self._initialized, "Thread.__init__() was not called"
status = "initial"
if self.__started:
if self._started:
status = "started"
if self.__stopped:
if self._stopped:
status = "stopped"
if self.__daemonic:
if self._daemonic:
status = status + " daemon"
return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
def start(self):
if not self.__initialized:
if not self._initialized:
raise RuntimeError("thread.__init__() not called")
if self.__started:
if self._started:
raise RuntimeError("thread already started")
if __debug__:
self._note("%s.start(): starting thread", self)
_active_limbo_lock.acquire()
_limbo[self] = self
_active_limbo_lock.release()
_start_new_thread(self.__bootstrap, ())
self.__started = True
_start_new_thread(self._bootstrap, ())
self._started = True
_sleep(0.000001) # 1 usec, to let the thread run (Solaris hack)
def run(self):
if self.__target:
self.__target(*self.__args, **self.__kwargs)
if self._target:
self._target(*self._args, **self._kwargs)
def __bootstrap(self):
def _bootstrap(self):
# Wrapper around the real bootstrap code that ignores
# exceptions during interpreter cleanup. Those typically
# happen when a daemon thread wakes up at an unfortunate
@ -458,15 +458,15 @@ class Thread(_Verbose):
# reported. Also, we only suppress them for daemonic threads;
# if a non-daemonic encounters this, something else is wrong.
try:
self.__bootstrap_inner()
self._bootstrap_inner()
except:
if self.__daemonic and _sys is None:
if self._daemonic and _sys is None:
return
raise
def __bootstrap_inner(self):
def _bootstrap_inner(self):
try:
self.__started = True
self._started = True
_active_limbo_lock.acquire()
_active[_get_ident()] = self
del _limbo[self]
@ -490,7 +490,7 @@ class Thread(_Verbose):
if __debug__:
self._note("%s.__bootstrap(): unhandled exception", self)
# If sys.stderr is no more (most likely from interpreter
# shutdown) use self.__stderr. Otherwise still use sys (as in
# shutdown) use self._stderr. Otherwise still use sys (as in
# _sys) in case sys.stderr was redefined since the creation of
# self.
if _sys:
@ -500,21 +500,21 @@ class Thread(_Verbose):
# Do the best job possible w/o a huge amt. of code to
# approximate a traceback (code ideas from
# Lib/traceback.py)
exc_type, exc_value, exc_tb = self.__exc_info()
exc_type, exc_value, exc_tb = self._exc_info()
try:
print((
"Exception in thread " + self.getName() +
" (most likely raised during interpreter shutdown):"), file=self.__stderr)
" (most likely raised during interpreter shutdown):"), file=self._stderr)
print((
"Traceback (most recent call last):"), file=self.__stderr)
"Traceback (most recent call last):"), file=self._stderr)
while exc_tb:
print((
' File "%s", line %s, in %s' %
(exc_tb.tb_frame.f_code.co_filename,
exc_tb.tb_lineno,
exc_tb.tb_frame.f_code.co_name)), file=self.__stderr)
exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
exc_tb = exc_tb.tb_next
print(("%s: %s" % (exc_type, exc_value)), file=self.__stderr)
print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
# Make sure that exc_tb gets deleted since it is a memory
# hog; deleting everything else is just for thoroughness
finally:
@ -523,19 +523,19 @@ class Thread(_Verbose):
if __debug__:
self._note("%s.__bootstrap(): normal return", self)
finally:
self.__stop()
self._stop()
try:
self.__delete()
self._delete()
except:
pass
def __stop(self):
self.__block.acquire()
self.__stopped = True
self.__block.notifyAll()
self.__block.release()
def _stop(self):
self._block.acquire()
self._stopped = True
self._block.notifyAll()
self._block.release()
def __delete(self):
def _delete(self):
"Remove current thread from the dict of currently running threads."
# Notes about running with dummy_thread:
@ -570,60 +570,60 @@ class Thread(_Verbose):
_active_limbo_lock.release()
def join(self, timeout=None):
if not self.__initialized:
if not self._initialized:
raise RuntimeError("Thread.__init__() not called")
if not self.__started:
if not self._started:
raise RuntimeError("cannot join thread before it is started")
if self is currentThread():
raise RuntimeError("cannot join current thread")
if __debug__:
if not self.__stopped:
if not self._stopped:
self._note("%s.join(): waiting until thread stops", self)
self.__block.acquire()
self._block.acquire()
try:
if timeout is None:
while not self.__stopped:
self.__block.wait()
while not self._stopped:
self._block.wait()
if __debug__:
self._note("%s.join(): thread stopped", self)
else:
deadline = _time() + timeout
while not self.__stopped:
while not self._stopped:
delay = deadline - _time()
if delay <= 0:
if __debug__:
self._note("%s.join(): timed out", self)
break
self.__block.wait(delay)
self._block.wait(delay)
else:
if __debug__:
self._note("%s.join(): thread stopped", self)
finally:
self.__block.release()
self._block.release()
def getName(self):
assert self.__initialized, "Thread.__init__() not called"
return self.__name
assert self._initialized, "Thread.__init__() not called"
return self._name
def setName(self, name):
assert self.__initialized, "Thread.__init__() not called"
self.__name = str(name)
assert self._initialized, "Thread.__init__() not called"
self._name = str(name)
def isAlive(self):
assert self.__initialized, "Thread.__init__() not called"
return self.__started and not self.__stopped
assert self._initialized, "Thread.__init__() not called"
return self._started and not self._stopped
def isDaemon(self):
assert self.__initialized, "Thread.__init__() not called"
return self.__daemonic
assert self._initialized, "Thread.__init__() not called"
return self._daemonic
def setDaemon(self, daemonic):
if not self.__initialized:
if not self._initialized:
raise RuntimeError("Thread.__init__() not called")
if self.__started:
if self._started:
raise RuntimeError("cannot set daemon status of active thread");
self.__daemonic = daemonic
self._daemonic = daemonic
# The timer class was contributed by Itamar Shtull-Trauring
@ -663,7 +663,7 @@ class _MainThread(Thread):
def __init__(self):
Thread.__init__(self, name="MainThread")
self._Thread__started = True
self._started = True
_active_limbo_lock.acquire()
_active[_get_ident()] = self
_active_limbo_lock.release()
@ -672,7 +672,7 @@ class _MainThread(Thread):
return False
def _exitfunc(self):
self._Thread__stop()
self._stop()
t = _pickSomeNonDaemonThread()
if t:
if __debug__:
@ -682,7 +682,7 @@ class _MainThread(Thread):
t = _pickSomeNonDaemonThread()
if __debug__:
self._note("%s: exiting", self)
self._Thread__delete()
self._delete()
def _pickSomeNonDaemonThread():
for t in enumerate():
@ -707,9 +707,9 @@ class _DummyThread(Thread):
# Thread.__block consumes an OS-level locking primitive, which
# can never be used by a _DummyThread. Since a _DummyThread
# instance is immortal, that's bad, so release this resource.
del self._Thread__block
del self._block
self._Thread__started = True
self._started = True
_active_limbo_lock.acquire()
_active[_get_ident()] = self
_active_limbo_lock.release()