Merged revisions 64125 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r64125 | benjamin.peterson | 2008-06-11 12:27:50 -0500 (Wed, 11 Jun 2008) | 2 lines

  give the threading API PEP 8 names
........
This commit is contained in:
Benjamin Peterson 2008-06-11 19:14:14 +00:00
parent 559e5d7f4d
commit 672b8031a8
20 changed files with 126 additions and 131 deletions

View file

@ -15,7 +15,7 @@ The :mod:`dummy_threading` module is provided for situations where
This module defines the following functions and objects: This module defines the following functions and objects:
.. function:: activeCount() .. function:: active_count()
Return the number of :class:`Thread` objects currently alive. The returned Return the number of :class:`Thread` objects currently alive. The returned
count is equal to the length of the list returned by :func:`enumerate`. count is equal to the length of the list returned by :func:`enumerate`.
@ -29,7 +29,7 @@ This module defines the following functions and objects:
thread. thread.
.. function:: currentThread() .. function:: current_thread()
Return the current :class:`Thread` object, corresponding to the caller's thread Return the current :class:`Thread` object, corresponding to the caller's thread
of control. If the caller's thread of control was not created through the of control. If the caller's thread of control was not created through the
@ -39,10 +39,10 @@ This module defines the following functions and objects:
.. function:: enumerate() .. function:: enumerate()
Return a list of all :class:`Thread` objects currently alive. The list includes Return a list of all :class:`Thread` objects currently alive. The list
daemonic threads, dummy thread objects created by :func:`currentThread`, and the includes daemonic threads, dummy thread objects created by
main thread. It excludes terminated threads and threads that have not yet been :func:`current_thread`, and the main thread. It excludes terminated threads
started. and threads that have not yet been started.
.. function:: Event() .. function:: Event()
@ -387,7 +387,7 @@ needs to wake up one consumer thread.
lock, its caller should. lock, its caller should.
.. method:: Condition.notifyAll() .. method:: Condition.notify_all()
Wake up all threads waiting on this condition. This method acts like Wake up all threads waiting on this condition. This method acts like
:meth:`notify`, but wakes up all waiting threads instead of one. If the calling :meth:`notify`, but wakes up all waiting threads instead of one. If the calling
@ -544,12 +544,12 @@ Other threads can call a thread's :meth:`join` method. This blocks the calling
thread until the thread whose :meth:`join` method is called is terminated. thread until the thread whose :meth:`join` method is called is terminated.
A thread has a name. The name can be passed to the constructor, set with the A thread has a name. The name can be passed to the constructor, set with the
:meth:`setName` method, and retrieved with the :meth:`getName` method. :meth:`set_name` method, and retrieved with the :meth:`get_name` method.
A thread can be flagged as a "daemon thread". The significance of this flag is A thread can be flagged as a "daemon thread". The significance of this flag is
that the entire Python program exits when only daemon threads are left. The that the entire Python program exits when only daemon threads are left. The
initial value is inherited from the creating thread. The flag can be set with initial value is inherited from the creating thread. The flag can be set with
the :meth:`setDaemon` method and retrieved with the :meth:`isDaemon` method. the :meth:`set_daemon` method and retrieved with the :meth:`is_daemon` method.
There is a "main thread" object; this corresponds to the initial thread of There is a "main thread" object; this corresponds to the initial thread of
control in the Python program. It is not a daemon thread. control in the Python program. It is not a daemon thread.
@ -629,12 +629,12 @@ impossible to detect the termination of alien threads.
raises the same exception. raises the same exception.
.. method:: Thread.getName() .. method:: Thread.get_name()
Return the thread's name. Return the thread's name.
.. method:: Thread.setName(name) .. method:: Thread.set_name(name)
Set the thread's name. Set the thread's name.
@ -643,18 +643,16 @@ impossible to detect the termination of alien threads.
constructor. constructor.
.. method:: Thread.getIdent() .. method:: Thread.get_ident()
Return the 'thread identifier' of this thread or None if the thread has not Return the 'thread identifier' of this thread or None if the thread has not
been started. This is a nonzero integer. See the :mod:`thread` module's been started. This is a nonzero integer. See the :func:`thread.get_ident()`
:func:`get_ident()` function. Thread identifiers may be recycled when a function. Thread identifiers may be recycled when a thread exits and another
thread exits and another thread is created. The identifier is returned thread is created. The identifier is returned even after the thread has
even after the thread has exited. exited.
.. versionadded:: 2.6
.. method:: Thread.isAlive() .. method:: Thread.is_alive()
Return whether the thread is alive. Return whether the thread is alive.
@ -663,12 +661,12 @@ impossible to detect the termination of alien threads.
returns a list of all alive threads. returns a list of all alive threads.
.. method:: Thread.isDaemon() .. method:: Thread.is_daemon()
Return the thread's daemon flag. Return the thread's daemon flag.
.. method:: Thread.setDaemon(daemonic) .. method:: Thread.set_daemon(daemonic)
Set the thread's daemon flag to the Boolean value *daemonic*. This must be Set the thread's daemon flag to the Boolean value *daemonic*. This must be
called before :meth:`start` is called, otherwise :exc:`RuntimeError` is raised. called before :meth:`start` is called, otherwise :exc:`RuntimeError` is raised.

View file

@ -161,16 +161,16 @@ class _localbase(object):
# __init__ being called, to make sure we don't call it # __init__ being called, to make sure we don't call it
# again ourselves. # again ourselves.
dict = object.__getattribute__(self, '__dict__') dict = object.__getattribute__(self, '__dict__')
currentThread().__dict__[key] = dict current_thread().__dict__[key] = dict
return self return self
def _patch(self): def _patch(self):
key = object.__getattribute__(self, '_local__key') key = object.__getattribute__(self, '_local__key')
d = currentThread().__dict__.get(key) d = current_thread().__dict__.get(key)
if d is None: if d is None:
d = {} d = {}
currentThread().__dict__[key] = d current_thread().__dict__[key] = d
object.__setattr__(self, '__dict__', d) object.__setattr__(self, '__dict__', d)
# we have a new instance dict, so call out __init__ if we have # we have a new instance dict, so call out __init__ if we have
@ -237,4 +237,4 @@ class local(_localbase):
except KeyError: except KeyError:
pass # didn't have anything in this thread pass # didn't have anything in this thread
from threading import currentThread, RLock from threading import current_thread, RLock

View file

@ -258,7 +258,7 @@ class LogRecord:
self.relativeCreated = (self.created - _startTime) * 1000 self.relativeCreated = (self.created - _startTime) * 1000
if logThreads and thread: if logThreads and thread:
self.thread = thread.get_ident() self.thread = thread.get_ident()
self.threadName = threading.currentThread().getName() self.threadName = threading.current_thread().get_name()
else: else:
self.thread = None self.thread = None
self.threadName = None self.threadName = None

View file

@ -48,24 +48,17 @@ class DummyProcess(threading.Thread):
threading.Thread.start(self) threading.Thread.start(self)
def get_exitcode(self): def get_exitcode(self):
if self._start_called and not self.isAlive(): if self._start_called and not self.is_alive():
return 0 return 0
else: else:
return None return None
# XXX
if sys.version_info < (3, 0): is_alive = threading.Thread.is_alive
is_alive = threading.Thread.isAlive.__func__ get_name = threading.Thread.get_name
get_name = threading.Thread.getName.__func__ set_name = threading.Thread.set_name
set_name = threading.Thread.setName.__func__ is_daemon = threading.Thread.is_daemon
is_daemon = threading.Thread.isDaemon.__func__ set_daemon = threading.Thread.set_daemon
set_daemon = threading.Thread.setDaemon.__func__
else:
is_alive = threading.Thread.isAlive
get_name = threading.Thread.getName
set_name = threading.Thread.setName
is_daemon = threading.Thread.isDaemon
set_daemon = threading.Thread.setDaemon
# #
# #
@ -74,22 +67,22 @@ class DummyProcess(threading.Thread):
class Condition(threading._Condition): class Condition(threading._Condition):
# XXX # XXX
if sys.version_info < (3, 0): if sys.version_info < (3, 0):
notify_all = threading._Condition.notifyAll.__func__ notify_all = threading._Condition.notify_all.__func__
else: else:
notify_all = threading._Condition.notifyAll notify_all = threading._Condition.notify_all
# #
# #
# #
Process = DummyProcess Process = DummyProcess
current_process = threading.currentThread current_process = threading.current_thread
current_process()._children = weakref.WeakKeyDictionary() current_process()._children = weakref.WeakKeyDictionary()
def active_children(): def active_children():
children = current_process()._children children = current_process()._children
for p in list(children): for p in list(children):
if not p.isAlive(): if not p.is_alive():
children.pop(p, None) children.pop(p, None)
return list(children) return list(children)

View file

@ -169,7 +169,7 @@ class Server(object):
except (OSError, IOError): except (OSError, IOError):
continue continue
t = threading.Thread(target=self.handle_request, args=(c,)) t = threading.Thread(target=self.handle_request, args=(c,))
t.setDaemon(True) t.set_daemon(True)
t.start() t.start()
except (KeyboardInterrupt, SystemExit): except (KeyboardInterrupt, SystemExit):
pass pass
@ -216,7 +216,7 @@ class Server(object):
Handle requests from the proxies in a particular process/thread Handle requests from the proxies in a particular process/thread
''' '''
util.debug('starting server thread to service %r', util.debug('starting server thread to service %r',
threading.currentThread().getName()) threading.current_thread().get_name())
recv = conn.recv recv = conn.recv
send = conn.send send = conn.send
@ -266,7 +266,7 @@ class Server(object):
except EOFError: except EOFError:
util.debug('got EOF -- exiting thread serving %r', util.debug('got EOF -- exiting thread serving %r',
threading.currentThread().getName()) threading.current_thread().get_name())
sys.exit(0) sys.exit(0)
except Exception: except Exception:
@ -279,7 +279,7 @@ class Server(object):
send(('#UNSERIALIZABLE', repr(msg))) send(('#UNSERIALIZABLE', repr(msg)))
except Exception as e: except Exception as e:
util.info('exception in thread serving %r', util.info('exception in thread serving %r',
threading.currentThread().getName()) threading.current_thread().get_name())
util.info(' ... message was %r', msg) util.info(' ... message was %r', msg)
util.info(' ... exception was %r', e) util.info(' ... exception was %r', e)
conn.close() conn.close()
@ -401,7 +401,7 @@ class Server(object):
''' '''
Spawn a new thread to serve this connection Spawn a new thread to serve this connection
''' '''
threading.currentThread().setName(name) threading.current_thread().set_name(name)
c.send(('#RETURN', None)) c.send(('#RETURN', None))
self.serve_client(c) self.serve_client(c)
@ -715,8 +715,8 @@ class BaseProxy(object):
def _connect(self): def _connect(self):
util.debug('making connection to manager') util.debug('making connection to manager')
name = current_process().get_name() name = current_process().get_name()
if threading.currentThread().getName() != 'MainThread': if threading.current_thread().get_name() != 'MainThread':
name += '|' + threading.currentThread().getName() name += '|' + threading.current_thread().get_name()
conn = self._Client(self._token.address, authkey=self._authkey) conn = self._Client(self._token.address, authkey=self._authkey)
dispatch(conn, None, 'accept_connection', (name,)) dispatch(conn, None, 'accept_connection', (name,))
self._tls.connection = conn self._tls.connection = conn
@ -729,7 +729,7 @@ class BaseProxy(object):
conn = self._tls.connection conn = self._tls.connection
except AttributeError: except AttributeError:
util.debug('thread %r does not own a connection', util.debug('thread %r does not own a connection',
threading.currentThread().getName()) threading.current_thread().get_name())
self._connect() self._connect()
conn = self._tls.connection conn = self._tls.connection
@ -790,7 +790,7 @@ class BaseProxy(object):
# the process owns no more references to objects for this manager # the process owns no more references to objects for this manager
if not idset and hasattr(tls, 'connection'): if not idset and hasattr(tls, 'connection'):
util.debug('thread %r has no more proxies so closing conn', util.debug('thread %r has no more proxies so closing conn',
threading.currentThread().getName()) threading.current_thread().get_name())
tls.connection.close() tls.connection.close()
del tls.connection del tls.connection
@ -969,13 +969,13 @@ class AcquirerProxy(BaseProxy):
class ConditionProxy(AcquirerProxy): class ConditionProxy(AcquirerProxy):
# XXX will Condition.notfyAll() name be available in Py3.0? # XXX will Condition.notfyAll() name be available in Py3.0?
_exposed_ = ('acquire', 'release', 'wait', 'notify', 'notifyAll') _exposed_ = ('acquire', 'release', 'wait', 'notify', 'notify_all')
def wait(self, timeout=None): def wait(self, timeout=None):
return self._callmethod('wait', (timeout,)) return self._callmethod('wait', (timeout,))
def notify(self): def notify(self):
return self._callmethod('notify') return self._callmethod('notify')
def notify_all(self): def notify_all(self):
return self._callmethod('notifyAll') return self._callmethod('notify_all')
class EventProxy(BaseProxy): class EventProxy(BaseProxy):
# XXX will Event.isSet name be available in Py3.0? # XXX will Event.isSet name be available in Py3.0?

View file

@ -107,7 +107,7 @@ class Pool(object):
target=Pool._handle_tasks, target=Pool._handle_tasks,
args=(self._taskqueue, self._quick_put, self._outqueue, self._pool) args=(self._taskqueue, self._quick_put, self._outqueue, self._pool)
) )
self._task_handler.setDaemon(True) self._task_handler.set_daemon(True)
self._task_handler._state = RUN self._task_handler._state = RUN
self._task_handler.start() self._task_handler.start()
@ -115,7 +115,7 @@ class Pool(object):
target=Pool._handle_results, target=Pool._handle_results,
args=(self._outqueue, self._quick_get, self._cache) args=(self._outqueue, self._quick_get, self._cache)
) )
self._result_handler.setDaemon(True) self._result_handler.set_daemon(True)
self._result_handler._state = RUN self._result_handler._state = RUN
self._result_handler.start() self._result_handler.start()
@ -213,7 +213,7 @@ class Pool(object):
@staticmethod @staticmethod
def _handle_tasks(taskqueue, put, outqueue, pool): def _handle_tasks(taskqueue, put, outqueue, pool):
thread = threading.currentThread() thread = threading.current_thread()
for taskseq, set_length in iter(taskqueue.get, None): for taskseq, set_length in iter(taskqueue.get, None):
i = -1 i = -1
@ -252,7 +252,7 @@ class Pool(object):
@staticmethod @staticmethod
def _handle_results(outqueue, get, cache): def _handle_results(outqueue, get, cache):
thread = threading.currentThread() thread = threading.current_thread()
while 1: while 1:
try: try:
@ -346,7 +346,7 @@ class Pool(object):
# task_handler may be blocked trying to put items on inqueue # task_handler may be blocked trying to put items on inqueue
debug('removing tasks from inqueue until task handler finished') debug('removing tasks from inqueue until task handler finished')
inqueue._rlock.acquire() inqueue._rlock.acquire()
while task_handler.isAlive() and inqueue._reader.poll(): while task_handler.is_alive() and inqueue._reader.poll():
inqueue._reader.recv() inqueue._reader.recv()
time.sleep(0) time.sleep(0)
@ -362,7 +362,7 @@ class Pool(object):
debug('helping task handler/workers to finish') debug('helping task handler/workers to finish')
cls._help_stuff_finish(inqueue, task_handler, len(pool)) cls._help_stuff_finish(inqueue, task_handler, len(pool))
assert result_handler.isAlive() or len(cache) == 0 assert result_handler.is_alive() or len(cache) == 0
result_handler._state = TERMINATE result_handler._state = TERMINATE
outqueue.put(None) # sentinel outqueue.put(None) # sentinel
@ -591,6 +591,6 @@ class ThreadPool(Pool):
try: try:
inqueue.queue.clear() inqueue.queue.clear()
inqueue.queue.extend([None] * size) inqueue.queue.extend([None] * size)
inqueue.not_empty.notifyAll() inqueue.not_empty.notify_all()
finally: finally:
inqueue.not_empty.release() inqueue.not_empty.release()

View file

@ -155,7 +155,7 @@ class Queue(object):
self._wlock, self._writer.close), self._wlock, self._writer.close),
name='QueueFeederThread' name='QueueFeederThread'
) )
self._thread.setDaemon(True) self._thread.set_daemon(True)
debug('doing self._thread.start()') debug('doing self._thread.start()')
self._thread.start() self._thread.start()

View file

@ -84,7 +84,7 @@ def _get_listener():
debug('starting listener and thread for sending handles') debug('starting listener and thread for sending handles')
_listener = Listener(authkey=current_process().get_authkey()) _listener = Listener(authkey=current_process().get_authkey())
t = threading.Thread(target=_serve) t = threading.Thread(target=_serve)
t.setDaemon(True) t.set_daemon(True)
t.start() t.start()
finally: finally:
_lock.release() _lock.release()

View file

@ -109,8 +109,8 @@ class Lock(SemLock):
try: try:
if self._semlock._is_mine(): if self._semlock._is_mine():
name = current_process().get_name() name = current_process().get_name()
if threading.currentThread().getName() != 'MainThread': if threading.current_thread().get_name() != 'MainThread':
name += '|' + threading.currentThread().getName() name += '|' + threading.current_thread().get_name()
elif self._semlock._get_value() == 1: elif self._semlock._get_value() == 1:
name = 'None' name = 'None'
elif self._semlock._count() > 0: elif self._semlock._count() > 0:
@ -134,8 +134,8 @@ class RLock(SemLock):
try: try:
if self._semlock._is_mine(): if self._semlock._is_mine():
name = current_process().get_name() name = current_process().get_name()
if threading.currentThread().getName() != 'MainThread': if threading.current_thread().get_name() != 'MainThread':
name += '|' + threading.currentThread().getName() name += '|' + threading.current_thread().get_name()
count = self._semlock._count() count = self._semlock._count()
elif self._semlock._get_value() == 1: elif self._semlock._get_value() == 1:
name, count = 'None', 0 name, count = 'None', 0

View file

@ -62,7 +62,7 @@ class Queue:
if unfinished <= 0: if unfinished <= 0:
if unfinished < 0: if unfinished < 0:
raise ValueError('task_done() called too many times') raise ValueError('task_done() called too many times')
self.all_tasks_done.notifyAll() self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished self.unfinished_tasks = unfinished
finally: finally:
self.all_tasks_done.release() self.all_tasks_done.release()

View file

@ -16,7 +16,7 @@ class DummyThreadingTestCase(unittest.TestCase):
#delay = random.random() * 2 #delay = random.random() * 2
delay = 0 delay = 0
if support.verbose: if support.verbose:
print('task', self.getName(), 'will run for', delay, 'sec') print('task', self.get_name(), 'will run for', delay, 'sec')
sema.acquire() sema.acquire()
mutex.acquire() mutex.acquire()
running += 1 running += 1
@ -25,11 +25,11 @@ class DummyThreadingTestCase(unittest.TestCase):
mutex.release() mutex.release()
time.sleep(delay) time.sleep(delay)
if support.verbose: if support.verbose:
print('task', self.getName(), 'done') print('task', self.get_name(), 'done')
mutex.acquire() mutex.acquire()
running -= 1 running -= 1
if support.verbose: if support.verbose:
print(self.getName(), 'is finished.', running, 'tasks are running') print(self.get_name(), 'is finished.', running, 'tasks are running')
mutex.release() mutex.release()
sema.release() sema.release()

View file

@ -632,7 +632,7 @@ class _TestCondition(BaseTestCase):
p.start() p.start()
p = threading.Thread(target=self.f, args=(cond, sleeping, woken)) p = threading.Thread(target=self.f, args=(cond, sleeping, woken))
p.setDaemon(True) p.set_daemon(True)
p.start() p.start()
# wait for both children to start sleeping # wait for both children to start sleeping
@ -679,7 +679,7 @@ class _TestCondition(BaseTestCase):
t = threading.Thread(target=self.f, t = threading.Thread(target=self.f,
args=(cond, sleeping, woken, TIMEOUT1)) args=(cond, sleeping, woken, TIMEOUT1))
t.setDaemon(True) t.set_daemon(True)
t.start() t.start()
# wait for them all to sleep # wait for them all to sleep
@ -701,7 +701,7 @@ class _TestCondition(BaseTestCase):
p.start() p.start()
t = threading.Thread(target=self.f, args=(cond, sleeping, woken)) t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
t.setDaemon(True) t.set_daemon(True)
t.start() t.start()
# wait for them to all sleep # wait for them to all sleep

View file

@ -52,11 +52,11 @@ class BlockingTestMixin:
self.t.start() self.t.start()
self.result = block_func(*block_args) self.result = block_func(*block_args)
# If block_func returned before our thread made the call, we failed! # If block_func returned before our thread made the call, we failed!
if not self.t.startedEvent.isSet(): if not self.t.startedEvent.is_set():
self.fail("blocking function '%r' appeared not to block" % self.fail("blocking function '%r' appeared not to block" %
block_func) block_func)
self.t.join(10) # make sure the thread terminates self.t.join(10) # make sure the thread terminates
if self.t.isAlive(): if self.t.is_alive():
self.fail("trigger function '%r' appeared to not return" % self.fail("trigger function '%r' appeared to not return" %
trigger_func) trigger_func)
return self.result return self.result
@ -76,10 +76,10 @@ class BlockingTestMixin:
expected_exception_class) expected_exception_class)
finally: finally:
self.t.join(10) # make sure the thread terminates self.t.join(10) # make sure the thread terminates
if self.t.isAlive(): if self.t.is_alive():
self.fail("trigger function '%r' appeared to not return" % self.fail("trigger function '%r' appeared to not return" %
trigger_func) trigger_func)
if not self.t.startedEvent.isSet(): if not self.t.startedEvent.is_set():
self.fail("trigger thread ended but event never set") self.fail("trigger thread ended but event never set")

View file

@ -109,7 +109,7 @@ def debugging_server(serv, serv_evt, client_evt):
# when the client conversation is finished, it will # when the client conversation is finished, it will
# set client_evt, and it's then ok to kill the server # set client_evt, and it's then ok to kill the server
if client_evt.isSet(): if client_evt.is_set():
serv.close() serv.close()
break break
@ -118,7 +118,7 @@ def debugging_server(serv, serv_evt, client_evt):
except socket.timeout: except socket.timeout:
pass pass
finally: finally:
if not client_evt.isSet(): if not client_evt.is_set():
# allow some time for the client to read the result # allow some time for the client to read the result
time.sleep(0.5) time.sleep(0.5)
serv.close() serv.close()

View file

@ -108,7 +108,7 @@ class ThreadableTest:
self.clientRun, (test_method,)) self.clientRun, (test_method,))
self.__setUp() self.__setUp()
if not self.server_ready.isSet(): if not self.server_ready.is_set():
self.server_ready.set() self.server_ready.set()
self.client_ready.wait() self.client_ready.wait()

View file

@ -139,7 +139,7 @@ class SocketServerTest(unittest.TestCase):
# Time between requests is short enough that we won't wake # Time between requests is short enough that we won't wake
# up spuriously too many times. # up spuriously too many times.
kwargs={'poll_interval':0.01}) kwargs={'poll_interval':0.01})
t.setDaemon(True) # In case this function raises. t.set_daemon(True) # In case this function raises.
t.start() t.start()
if verbose: print("server running") if verbose: print("server running")
for i in range(3): for i in range(3):

View file

@ -34,7 +34,7 @@ class TestThread(threading.Thread):
delay = random.random() / 10000.0 delay = random.random() / 10000.0
if verbose: if verbose:
print('task %s will run for %.1f usec' % print('task %s will run for %.1f usec' %
(self.getName(), delay * 1e6)) (self.get_name(), delay * 1e6))
with self.sema: with self.sema:
with self.mutex: with self.mutex:
@ -45,13 +45,15 @@ class TestThread(threading.Thread):
time.sleep(delay) time.sleep(delay)
if verbose: if verbose:
print('task', self.getName(), 'done') print('task', self.get_name(), 'done')
with self.mutex: with self.mutex:
self.nrunning.dec() self.nrunning.dec()
self.testcase.assert_(self.nrunning.get() >= 0) self.testcase.assert_(self.nrunning.get() >= 0)
if verbose: if verbose:
print('%s is finished. %d tasks are running' % print('%s is finished. %d tasks are running' %
(self.getName(), self.nrunning.get())) (self.get_name(), self.nrunning.get()))
class ThreadTests(unittest.TestCase): class ThreadTests(unittest.TestCase):
@ -72,7 +74,7 @@ class ThreadTests(unittest.TestCase):
for i in range(NUMTASKS): for i in range(NUMTASKS):
t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
threads.append(t) threads.append(t)
self.failUnlessEqual(t.getIdent(), None) self.failUnlessEqual(t.get_ident(), None)
self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t))) self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t)))
t.start() t.start()
@ -80,8 +82,8 @@ class ThreadTests(unittest.TestCase):
print('waiting for all tasks to complete') print('waiting for all tasks to complete')
for t in threads: for t in threads:
t.join(NUMTASKS) t.join(NUMTASKS)
self.assert_(not t.isAlive()) self.assert_(not t.is_alive())
self.failIfEqual(t.getIdent(), 0) self.failIfEqual(t.get_ident(), 0)
self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t))) self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
if verbose: if verbose:
print('all tasks done') print('all tasks done')
@ -171,7 +173,7 @@ class ThreadTests(unittest.TestCase):
worker_saw_exception.set() worker_saw_exception.set()
t = Worker() t = Worker()
t.setDaemon(True) # so if this fails, we don't hang Python at shutdown t.set_daemon(True) # so if this fails, we don't hang Python at shutdown
t.start() t.start()
if verbose: if verbose:
print(" started worker thread") print(" started worker thread")
@ -257,12 +259,12 @@ class ThreadTests(unittest.TestCase):
print('program blocked; aborting') print('program blocked; aborting')
os._exit(2) os._exit(2)
t = threading.Thread(target=killer) t = threading.Thread(target=killer)
t.setDaemon(True) t.set_daemon(True)
t.start() t.start()
# This is the trace function # This is the trace function
def func(frame, event, arg): def func(frame, event, arg):
threading.currentThread() threading.current_thread()
return func return func
sys.settrace(func) sys.settrace(func)
@ -347,8 +349,8 @@ class ThreadingExceptionTests(unittest.TestCase):
self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize) self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
def test_joining_current_thread(self): def test_joining_current_thread(self):
currentThread = threading.currentThread() current_thread = threading.current_thread()
self.assertRaises(RuntimeError, currentThread.join); self.assertRaises(RuntimeError, current_thread.join);
def test_joining_inactive_thread(self): def test_joining_inactive_thread(self):
thread = threading.Thread() thread = threading.Thread()
@ -357,7 +359,7 @@ class ThreadingExceptionTests(unittest.TestCase):
def test_daemonize_active_thread(self): def test_daemonize_active_thread(self):
thread = threading.Thread() thread = threading.Thread()
thread.start() thread.start()
self.assertRaises(RuntimeError, thread.setDaemon, True) self.assertRaises(RuntimeError, thread.set_daemon, True)
def test_main(): def test_main():

View file

@ -38,5 +38,5 @@ for name, func, args in [
t = Worker(func, args) t = Worker(func, args)
t.start() t.start()
t.join(TIMEOUT) t.join(TIMEOUT)
if t.isAlive(): if t.is_alive():
errors.append("%s appeared to hang" % name) errors.append("%s appeared to hang" % name)

View file

@ -8,7 +8,7 @@ from traceback import format_exc as _format_exc
from collections import deque from collections import deque
# Rename some stuff so "from threading import *" is safe # Rename some stuff so "from threading import *" is safe
__all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event', __all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
'Timer', 'setprofile', 'settrace', 'local', 'stack_size'] 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
@ -40,7 +40,7 @@ if __debug__:
if self._verbose: if self._verbose:
format = format % args format = format % args
format = "%s: %s\n" % ( format = "%s: %s\n" % (
currentThread().getName(), format) current_thread().get_name(), format)
_sys.stderr.write(format) _sys.stderr.write(format)
else: else:
@ -83,11 +83,11 @@ class _RLock(_Verbose):
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.get_name(),
self._count) self._count)
def acquire(self, blocking=1): def acquire(self, blocking=1):
me = currentThread() me = current_thread()
if self._owner is me: if self._owner is me:
self._count = self._count + 1 self._count = self._count + 1
if __debug__: if __debug__:
@ -107,7 +107,7 @@ class _RLock(_Verbose):
__enter__ = acquire __enter__ = acquire
def release(self): def release(self):
if self._owner is not currentThread(): if self._owner is not current_thread():
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:
@ -141,7 +141,7 @@ class _RLock(_Verbose):
return (count, owner) return (count, owner)
def _is_owned(self): def _is_owned(self):
return self._owner is currentThread() return self._owner is current_thread()
def Condition(*args, **kwargs): def Condition(*args, **kwargs):
@ -190,7 +190,7 @@ class _Condition(_Verbose):
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 current_thread.
# 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()
@ -258,7 +258,7 @@ class _Condition(_Verbose):
except ValueError: except ValueError:
pass pass
def notifyAll(self): def notify_all(self):
self.notify(len(self._waiters)) self.notify(len(self._waiters))
@ -337,14 +337,14 @@ class _Event(_Verbose):
self._cond = Condition(Lock()) self._cond = Condition(Lock())
self._flag = False self._flag = False
def isSet(self): def is_set(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.notify_all()
finally: finally:
self._cond.release() self._cond.release()
@ -412,12 +412,12 @@ class Thread(_Verbose):
def _set_daemon(self): def _set_daemon(self):
# Overridden in _MainThread and _DummyThread # Overridden in _MainThread and _DummyThread
return currentThread().isDaemon() return current_thread().is_daemon()
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.isSet(): if self._started.is_set():
status = "started" status = "started"
if self._stopped: if self._stopped:
status = "stopped" status = "stopped"
@ -431,7 +431,7 @@ class Thread(_Verbose):
if not self._initialized: if not self._initialized:
raise RuntimeError("thread.__init__() not called") raise RuntimeError("thread.__init__() not called")
if self._started.isSet(): if self._started.is_set():
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)
@ -502,7 +502,7 @@ class Thread(_Verbose):
# self. # self.
if _sys: if _sys:
_sys.stderr.write("Exception in thread %s:\n%s\n" % _sys.stderr.write("Exception in thread %s:\n%s\n" %
(self.getName(), _format_exc())) (self.get_name(), _format_exc()))
else: else:
# 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
@ -510,7 +510,7 @@ class Thread(_Verbose):
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.get_name() +
" (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)
@ -549,7 +549,7 @@ class Thread(_Verbose):
def _stop(self): def _stop(self):
self._block.acquire() self._block.acquire()
self._stopped = True self._stopped = True
self._block.notifyAll() self._block.notify_all()
self._block.release() self._block.release()
def _delete(self): def _delete(self):
@ -582,7 +582,7 @@ class Thread(_Verbose):
# There must not be any python code between the previous line # There must not be any python code between the previous line
# and after the lock is released. Otherwise a tracing function # and after the lock is released. Otherwise a tracing function
# could try to acquire the lock again in the same thread, (in # could try to acquire the lock again in the same thread, (in
# currentThread()), and would block. # current_thread()), and would block.
except KeyError: except KeyError:
if 'dummy_threading' not in _sys.modules: if 'dummy_threading' not in _sys.modules:
raise raise
@ -590,9 +590,9 @@ class Thread(_Verbose):
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.isSet(): if not self._started.is_set():
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 current_thread():
raise RuntimeError("cannot join current thread") raise RuntimeError("cannot join current thread")
if __debug__: if __debug__:
@ -621,30 +621,30 @@ class Thread(_Verbose):
finally: finally:
self._block.release() self._block.release()
def getName(self): def get_name(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 set_name(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 getIdent(self): def get_ident(self):
assert self._initialized, "Thread.__init__() not called" assert self._initialized, "Thread.__init__() not called"
return self._ident return self._ident
def isAlive(self): def is_alive(self):
assert self._initialized, "Thread.__init__() not called" assert self._initialized, "Thread.__init__() not called"
return self._started.isSet() and not self._stopped return self._started.is_set() and not self._stopped
def isDaemon(self): def is_daemon(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 set_daemon(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.isSet(): if self._started.is_set():
raise RuntimeError("cannot set daemon status of active thread"); raise RuntimeError("cannot set daemon status of active thread");
self._daemonic = daemonic self._daemonic = daemonic
@ -675,7 +675,7 @@ class _Timer(Thread):
def run(self): def run(self):
self.finished.wait(self.interval) self.finished.wait(self.interval)
if not self.finished.isSet(): if not self.finished.is_set():
self.function(*self.args, **self.kwargs) self.function(*self.args, **self.kwargs)
self.finished.set() self.finished.set()
@ -709,16 +709,16 @@ class _MainThread(Thread):
def _pickSomeNonDaemonThread(): def _pickSomeNonDaemonThread():
for t in enumerate(): for t in enumerate():
if not t.isDaemon() and t.isAlive(): if not t.is_daemon() and t.is_alive():
return t return t
return None return None
# Dummy thread class to represent threads not started here. # Dummy thread class to represent threads not started here.
# These aren't garbage collected when they die, nor can they be waited for. # These aren't garbage collected when they die, nor can they be waited for.
# If they invoke anything in threading.py that calls currentThread(), they # If they invoke anything in threading.py that calls current_thread(), they
# leave an entry in the _active dict forever after. # leave an entry in the _active dict forever after.
# Their purpose is to return *something* from currentThread(). # Their purpose is to return *something* from current_thread().
# They are marked as daemon threads so we won't wait for them # They are marked as daemon threads so we won't wait for them
# when we exit (conform previous semantics). # when we exit (conform previous semantics).
@ -747,14 +747,14 @@ class _DummyThread(Thread):
# Global API functions # Global API functions
def currentThread(): def current_thread():
try: try:
return _active[_get_ident()] return _active[_get_ident()]
except KeyError: except KeyError:
##print "currentThread(): no current thread for", _get_ident() ##print "current_thread(): no current thread for", _get_ident()
return _DummyThread() return _DummyThread()
def activeCount(): def active_count():
_active_limbo_lock.acquire() _active_limbo_lock.acquire()
count = len(_active) + len(_limbo) count = len(_active) + len(_limbo)
_active_limbo_lock.release() _active_limbo_lock.release()
@ -831,7 +831,7 @@ def _test():
counter = 0 counter = 0
while counter < self.quota: while counter < self.quota:
counter = counter + 1 counter = counter + 1
self.queue.put("%s.%d" % (self.getName(), counter)) self.queue.put("%s.%d" % (self.get_name(), counter))
_sleep(random() * 0.00001) _sleep(random() * 0.00001)

View file

@ -160,6 +160,8 @@ Library
- The test.test_support module has been renamed to test.support. - The test.test_support module has been renamed to test.support.
- The threading module API's were renamed to by PEP 8 complaint.
Tools/Demos Tools/Demos
----------- -----------