Commit d0648994 authored by Guido van Rossum's avatar Guido van Rossum

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

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