mirror of
https://github.com/python/cpython.git
synced 2024-12-01 22:04:04 +08:00
d23f8224e9
svn+ssh://pythondev@svn.python.org/python/trunk ........ r70712 | benjamin.peterson | 2009-03-30 10:15:38 -0500 (Mon, 30 Mar 2009) | 1 line don't rely on the order dict repr #5605 ........ r70714 | brett.cannon | 2009-03-30 10:20:53 -0500 (Mon, 30 Mar 2009) | 1 line Add an entry to developers.txt. ........ r70764 | martin.v.loewis | 2009-03-30 17:06:33 -0500 (Mon, 30 Mar 2009) | 2 lines Add several VM developers. ........ r70765 | georg.brandl | 2009-03-30 17:09:34 -0500 (Mon, 30 Mar 2009) | 1 line #5199: make warning about vars() assignment more visible. ........ r70769 | andrew.kuchling | 2009-03-30 17:29:53 -0500 (Mon, 30 Mar 2009) | 1 line Remove comment ........ r70770 | andrew.kuchling | 2009-03-30 17:30:20 -0500 (Mon, 30 Mar 2009) | 1 line Add several items and placeholders ........ r70771 | andrew.kuchling | 2009-03-30 17:31:11 -0500 (Mon, 30 Mar 2009) | 1 line Many edits ........ r70773 | georg.brandl | 2009-03-30 17:43:00 -0500 (Mon, 30 Mar 2009) | 1 line #5039: make it clear that the impl. note refers to CPython. ........ r70776 | andrew.kuchling | 2009-03-30 18:08:24 -0500 (Mon, 30 Mar 2009) | 1 line typo fix ........ r70777 | andrew.kuchling | 2009-03-30 18:09:46 -0500 (Mon, 30 Mar 2009) | 1 line Add more items ........ r70788 | andrew.kuchling | 2009-03-30 20:21:01 -0500 (Mon, 30 Mar 2009) | 1 line Add various items ........ r70789 | georg.brandl | 2009-03-30 20:25:15 -0500 (Mon, 30 Mar 2009) | 1 line Fix a wrong struct field assignment (docstring as closure). ........ r70824 | georg.brandl | 2009-03-31 10:43:20 -0500 (Tue, 31 Mar 2009) | 1 line #5519: remove reference to Kodos, which seems dead. ........ r70828 | georg.brandl | 2009-03-31 10:50:16 -0500 (Tue, 31 Mar 2009) | 1 line #5581: fget argument of abstractproperty is optional as well. ........ r70832 | georg.brandl | 2009-03-31 11:31:11 -0500 (Tue, 31 Mar 2009) | 1 line #1386675: specify WindowsError as the exception, because it has a winerror attribute that EnvironmentError doesnt have. ........ r70836 | georg.brandl | 2009-03-31 11:50:25 -0500 (Tue, 31 Mar 2009) | 1 line #5417: replace references to undocumented functions by ones to documented functions. ........ r70842 | georg.brandl | 2009-03-31 12:13:06 -0500 (Tue, 31 Mar 2009) | 1 line #970783: document PyObject_Generic[GS]etAttr. ........ r70851 | georg.brandl | 2009-03-31 13:26:55 -0500 (Tue, 31 Mar 2009) | 1 line #837577: note cryptic return value of spawn*e on invalid env dicts. ........ r70855 | georg.brandl | 2009-03-31 13:30:37 -0500 (Tue, 31 Mar 2009) | 1 line #5245: note that PyRun_SimpleString doesnt return on SystemExit. ........ r70857 | georg.brandl | 2009-03-31 13:33:10 -0500 (Tue, 31 Mar 2009) | 1 line #5227: note that Py_Main doesnt return on SystemExit. ........ r70866 | georg.brandl | 2009-03-31 14:06:57 -0500 (Tue, 31 Mar 2009) | 1 line #4882: document named group behavior a bit better. ........ r70867 | georg.brandl | 2009-03-31 14:10:35 -0500 (Tue, 31 Mar 2009) | 1 line #1096310: document usage of sys.__std*__ a bit better. ........ r70868 | georg.brandl | 2009-03-31 14:12:17 -0500 (Tue, 31 Mar 2009) | 1 line #5190: export make_option in __all__. ........ r70869 | georg.brandl | 2009-03-31 14:14:42 -0500 (Tue, 31 Mar 2009) | 1 line Fix-up unwanted change. ........ r70870 | georg.brandl | 2009-03-31 14:26:24 -0500 (Tue, 31 Mar 2009) | 1 line #4411: document mro() and __mro__. (I hope I got it right.) ........ r70871 | georg.brandl | 2009-03-31 14:30:56 -0500 (Tue, 31 Mar 2009) | 1 line #5618: fix typo. ........ r70872 | r.david.murray | 2009-03-31 14:31:17 -0500 (Tue, 31 Mar 2009) | 3 lines Delete out-of-date and little-known README from the test directory by consensus of devs at pycon sprint. ........ r70883 | georg.brandl | 2009-03-31 15:41:08 -0500 (Tue, 31 Mar 2009) | 1 line #1674032: return value of flag from Event.wait(). OKed by Guido. ........ r70885 | tarek.ziade | 2009-03-31 15:48:31 -0500 (Tue, 31 Mar 2009) | 1 line using log.warn for sys.stderr ........ r70893 | georg.brandl | 2009-03-31 15:56:32 -0500 (Tue, 31 Mar 2009) | 1 line #1530012: move TQS section before raw strings. ........ r70894 | benjamin.peterson | 2009-03-31 16:06:30 -0500 (Tue, 31 Mar 2009) | 1 line take the usual lock precautions around _active_limbo_lock ........ r70896 | georg.brandl | 2009-03-31 16:15:33 -0500 (Tue, 31 Mar 2009) | 1 line #5598: document DocFileSuite *args argument. ........ r70897 | benjamin.peterson | 2009-03-31 16:34:42 -0500 (Tue, 31 Mar 2009) | 1 line fix Thread.ident when it is the main thread or a dummy thread #5632 ........ r70903 | georg.brandl | 2009-03-31 16:45:18 -0500 (Tue, 31 Mar 2009) | 1 line #1676135: remove trailing slashes from --prefix argument. ........ r70905 | georg.brandl | 2009-03-31 17:03:40 -0500 (Tue, 31 Mar 2009) | 1 line #5563: more documentation for bdist_msi. ........ r70906 | georg.brandl | 2009-03-31 17:11:53 -0500 (Tue, 31 Mar 2009) | 1 line #1651995: fix _convert_ref for non-ASCII characters. ........ r70907 | georg.brandl | 2009-03-31 17:18:19 -0500 (Tue, 31 Mar 2009) | 1 line #3427: document correct return type for urlopen().info(). ........ r70915 | georg.brandl | 2009-03-31 17:40:16 -0500 (Tue, 31 Mar 2009) | 1 line #5018: remove confusing paragraph. ........ r70927 | georg.brandl | 2009-03-31 18:01:27 -0500 (Tue, 31 Mar 2009) | 1 line Dont shout to users. ........ r70933 | georg.brandl | 2009-03-31 19:04:33 -0500 (Tue, 31 Mar 2009) | 2 lines Issue #5635: Fix running test_sys with tracing enabled. ........ r70951 | georg.brandl | 2009-04-01 09:02:27 -0500 (Wed, 01 Apr 2009) | 1 line Add Maksim, who worked on several issues at the sprint. ........ r70960 | jesse.noller | 2009-04-01 11:42:19 -0500 (Wed, 01 Apr 2009) | 1 line Issue 3270: document Listener address restrictions on windows ........ r70962 | brett.cannon | 2009-04-01 12:07:16 -0500 (Wed, 01 Apr 2009) | 2 lines Ron DuPlain was given commit privileges at PyCon 2009 to work on 3to2. ........ r70963 | georg.brandl | 2009-04-01 12:46:01 -0500 (Wed, 01 Apr 2009) | 1 line #5655: fix docstring oversight. ........ r70964 | brett.cannon | 2009-04-01 12:52:13 -0500 (Wed, 01 Apr 2009) | 2 lines Paul Kippes was given commit privileges to work on 3to2. ........ r70998 | georg.brandl | 2009-04-01 16:54:21 -0500 (Wed, 01 Apr 2009) | 1 line In Pdb, stop assigning values to __builtin__._ which interferes with the one commonly installed by gettext. ........ r71001 | brett.cannon | 2009-04-01 18:01:12 -0500 (Wed, 01 Apr 2009) | 3 lines Add my initials to Misc/developers.txt. Names are now sorted by number of characters in the person's name. ........ r71006 | georg.brandl | 2009-04-01 18:32:17 -0500 (Wed, 01 Apr 2009) | 1 line Cache the f_locals dict of the current frame, since every access to frame.f_locals overrides its contents with the real locals which undoes modifications made by the debugging user. ........ r71008 | andrew.kuchling | 2009-04-01 19:02:14 -0500 (Wed, 01 Apr 2009) | 1 line Typo fix ........ r71010 | benjamin.peterson | 2009-04-01 19:11:52 -0500 (Wed, 01 Apr 2009) | 1 line fix markup ........ r71011 | benjamin.peterson | 2009-04-01 19:12:47 -0500 (Wed, 01 Apr 2009) | 1 line this should be :noindex: ........ r71019 | georg.brandl | 2009-04-01 21:00:01 -0500 (Wed, 01 Apr 2009) | 1 line Fix test_doctest, missed two assignments to curframe. ........ r71037 | r.david.murray | 2009-04-01 23:34:04 -0500 (Wed, 01 Apr 2009) | 6 lines Clarify that datetime strftime does not produce leap seconds and datetime strptime does not accept it in the strftime behavior section of the datetime docs. Closes issue 2568. ........ r71056 | georg.brandl | 2009-04-02 12:43:07 -0500 (Thu, 02 Apr 2009) | 2 lines Actually the displayhook should print the repr. ........ r71094 | vinay.sajip | 2009-04-03 05:23:18 -0500 (Fri, 03 Apr 2009) | 1 line Added warning about logging use from asynchronous signal handlers. ........ r71101 | andrew.kuchling | 2009-04-03 16:43:00 -0500 (Fri, 03 Apr 2009) | 1 line Add some items ........ r71102 | andrew.kuchling | 2009-04-03 16:44:49 -0500 (Fri, 03 Apr 2009) | 1 line Fix 'the the'; grammar fix ........ r71103 | andrew.kuchling | 2009-04-03 16:45:29 -0500 (Fri, 03 Apr 2009) | 1 line Fix 'the the' duplication ........ r71106 | vinay.sajip | 2009-04-03 16:58:16 -0500 (Fri, 03 Apr 2009) | 1 line Clarified warning about logging use from asynchronous signal handlers. ........ r71119 | raymond.hettinger | 2009-04-04 00:37:47 -0500 (Sat, 04 Apr 2009) | 1 line Add helpful link. ........ r71123 | r.david.murray | 2009-04-04 01:39:56 -0500 (Sat, 04 Apr 2009) | 2 lines Fix error in description of 'oct' (issue 5678). ........ r71149 | georg.brandl | 2009-04-04 08:42:39 -0500 (Sat, 04 Apr 2009) | 1 line #5642: clarify map() compatibility to the builtin. ........ r71150 | georg.brandl | 2009-04-04 08:45:49 -0500 (Sat, 04 Apr 2009) | 1 line #5601: clarify that webbrowser is not meant for file names. ........ r71203 | benjamin.peterson | 2009-04-04 18:46:34 -0500 (Sat, 04 Apr 2009) | 1 line note how using iter* are unsafe while mutating and document iter(dict) ........ r71212 | georg.brandl | 2009-04-05 05:24:20 -0500 (Sun, 05 Apr 2009) | 1 line #1742837: expand HTTP server docs, and fix SocketServer ones to document methods as methods, not functions. ........ r71214 | georg.brandl | 2009-04-05 05:29:57 -0500 (Sun, 05 Apr 2009) | 1 line Normalize spelling of Mac OS X. ........ r71215 | georg.brandl | 2009-04-05 05:32:26 -0500 (Sun, 05 Apr 2009) | 1 line Avoid sure signs of a diseased mind. ........ r71216 | georg.brandl | 2009-04-05 05:41:02 -0500 (Sun, 05 Apr 2009) | 1 line #1718017: document the relation of os.path and the posixpath, ntpath etc. modules better. ........ r71217 | georg.brandl | 2009-04-05 05:48:47 -0500 (Sun, 05 Apr 2009) | 1 line #1726172: dont raise an unexpected IndexError if a voidresp() call has an empty response. ........ r71221 | vinay.sajip | 2009-04-05 06:06:24 -0500 (Sun, 05 Apr 2009) | 1 line Issue #5695: Moved logging.captureWarnings() call inside with statement in WarningsTest.test_warnings. ........ r71240 | georg.brandl | 2009-04-05 09:40:06 -0500 (Sun, 05 Apr 2009) | 1 line #5370: doc update about unpickling objects with custom __getattr__ etc. methods. ........
486 lines
17 KiB
Python
486 lines
17 KiB
Python
# Very rudimentary test of threading module
|
|
|
|
import test.support
|
|
from test.support import verbose
|
|
import random
|
|
import re
|
|
import sys
|
|
import threading
|
|
import _thread
|
|
import time
|
|
import unittest
|
|
import weakref
|
|
|
|
# A trivial mutable counter.
|
|
class Counter(object):
|
|
def __init__(self):
|
|
self.value = 0
|
|
def inc(self):
|
|
self.value += 1
|
|
def dec(self):
|
|
self.value -= 1
|
|
def get(self):
|
|
return self.value
|
|
|
|
class TestThread(threading.Thread):
|
|
def __init__(self, name, testcase, sema, mutex, nrunning):
|
|
threading.Thread.__init__(self, name=name)
|
|
self.testcase = testcase
|
|
self.sema = sema
|
|
self.mutex = mutex
|
|
self.nrunning = nrunning
|
|
|
|
def run(self):
|
|
delay = random.random() / 10000.0
|
|
if verbose:
|
|
print('task %s will run for %.1f usec' %
|
|
(self.name, delay * 1e6))
|
|
|
|
with self.sema:
|
|
with self.mutex:
|
|
self.nrunning.inc()
|
|
if verbose:
|
|
print(self.nrunning.get(), 'tasks are running')
|
|
self.testcase.assert_(self.nrunning.get() <= 3)
|
|
|
|
time.sleep(delay)
|
|
if verbose:
|
|
print('task', self.name, 'done')
|
|
|
|
with self.mutex:
|
|
self.nrunning.dec()
|
|
self.testcase.assert_(self.nrunning.get() >= 0)
|
|
if verbose:
|
|
print('%s is finished. %d tasks are running' %
|
|
(self.name, self.nrunning.get()))
|
|
|
|
|
|
class ThreadTests(unittest.TestCase):
|
|
|
|
# Create a bunch of threads, let each do some work, wait until all are
|
|
# done.
|
|
def test_various_ops(self):
|
|
# This takes about n/3 seconds to run (about n/3 clumps of tasks,
|
|
# times about 1 second per clump).
|
|
NUMTASKS = 10
|
|
|
|
# no more than 3 of the 10 can run at once
|
|
sema = threading.BoundedSemaphore(value=3)
|
|
mutex = threading.RLock()
|
|
numrunning = Counter()
|
|
|
|
threads = []
|
|
|
|
for i in range(NUMTASKS):
|
|
t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
|
|
threads.append(t)
|
|
self.failUnlessEqual(t.ident, None)
|
|
self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t)))
|
|
t.start()
|
|
|
|
if verbose:
|
|
print('waiting for all tasks to complete')
|
|
for t in threads:
|
|
t.join(NUMTASKS)
|
|
self.assert_(not t.is_alive())
|
|
self.failIfEqual(t.ident, 0)
|
|
self.assertFalse(t.ident is None)
|
|
self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
|
|
if verbose:
|
|
print('all tasks done')
|
|
self.assertEqual(numrunning.get(), 0)
|
|
|
|
def test_ident_of_no_threading_threads(self):
|
|
# The ident still must work for the main thread and dummy threads.
|
|
self.assertFalse(threading.currentThread().ident is None)
|
|
def f():
|
|
ident.append(threading.currentThread().ident)
|
|
done.set()
|
|
done = threading.Event()
|
|
ident = []
|
|
_thread.start_new_thread(f, ())
|
|
done.wait()
|
|
self.assertFalse(ident[0] is None)
|
|
|
|
# run with a small(ish) thread stack size (256kB)
|
|
def test_various_ops_small_stack(self):
|
|
if verbose:
|
|
print('with 256kB thread stack size...')
|
|
try:
|
|
threading.stack_size(262144)
|
|
except _thread.error:
|
|
if verbose:
|
|
print('platform does not support changing thread stack size')
|
|
return
|
|
self.test_various_ops()
|
|
threading.stack_size(0)
|
|
|
|
# run with a large thread stack size (1MB)
|
|
def test_various_ops_large_stack(self):
|
|
if verbose:
|
|
print('with 1MB thread stack size...')
|
|
try:
|
|
threading.stack_size(0x100000)
|
|
except _thread.error:
|
|
if verbose:
|
|
print('platform does not support changing thread stack size')
|
|
return
|
|
self.test_various_ops()
|
|
threading.stack_size(0)
|
|
|
|
def test_foreign_thread(self):
|
|
# Check that a "foreign" thread can use the threading module.
|
|
def f(mutex):
|
|
# Acquiring an RLock forces an entry for the foreign
|
|
# thread to get made in the threading._active map.
|
|
r = threading.RLock()
|
|
r.acquire()
|
|
r.release()
|
|
mutex.release()
|
|
|
|
mutex = threading.Lock()
|
|
mutex.acquire()
|
|
tid = _thread.start_new_thread(f, (mutex,))
|
|
# Wait for the thread to finish.
|
|
mutex.acquire()
|
|
self.assert_(tid in threading._active)
|
|
self.assert_(isinstance(threading._active[tid],
|
|
threading._DummyThread))
|
|
del threading._active[tid]
|
|
|
|
# PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
|
|
# exposed at the Python level. This test relies on ctypes to get at it.
|
|
def test_PyThreadState_SetAsyncExc(self):
|
|
try:
|
|
import ctypes
|
|
except ImportError:
|
|
if verbose:
|
|
print("test_PyThreadState_SetAsyncExc can't import ctypes")
|
|
return # can't do anything
|
|
|
|
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
|
|
|
|
class AsyncExc(Exception):
|
|
pass
|
|
|
|
exception = ctypes.py_object(AsyncExc)
|
|
|
|
# `worker_started` is set by the thread when it's inside a try/except
|
|
# block waiting to catch the asynchronously set AsyncExc exception.
|
|
# `worker_saw_exception` is set by the thread upon catching that
|
|
# exception.
|
|
worker_started = threading.Event()
|
|
worker_saw_exception = threading.Event()
|
|
|
|
class Worker(threading.Thread):
|
|
def run(self):
|
|
self.id = _thread.get_ident()
|
|
self.finished = False
|
|
|
|
try:
|
|
while True:
|
|
worker_started.set()
|
|
time.sleep(0.1)
|
|
except AsyncExc:
|
|
self.finished = True
|
|
worker_saw_exception.set()
|
|
|
|
t = Worker()
|
|
t.daemon = True # so if this fails, we don't hang Python at shutdown
|
|
t.start()
|
|
if verbose:
|
|
print(" started worker thread")
|
|
|
|
# Try a thread id that doesn't make sense.
|
|
if verbose:
|
|
print(" trying nonsensical thread id")
|
|
result = set_async_exc(ctypes.c_long(-1), exception)
|
|
self.assertEqual(result, 0) # no thread states modified
|
|
|
|
# Now raise an exception in the worker thread.
|
|
if verbose:
|
|
print(" waiting for worker thread to get started")
|
|
ret = worker_started.wait()
|
|
self.assertTrue(ret)
|
|
if verbose:
|
|
print(" verifying worker hasn't exited")
|
|
self.assert_(not t.finished)
|
|
if verbose:
|
|
print(" attempting to raise asynch exception in worker")
|
|
result = set_async_exc(ctypes.c_long(t.id), exception)
|
|
self.assertEqual(result, 1) # one thread state modified
|
|
if verbose:
|
|
print(" waiting for worker to say it caught the exception")
|
|
worker_saw_exception.wait(timeout=10)
|
|
self.assert_(t.finished)
|
|
if verbose:
|
|
print(" all OK -- joining worker")
|
|
if t.finished:
|
|
t.join()
|
|
# else the thread is still running, and we have no way to kill it
|
|
|
|
def test_finalize_runnning_thread(self):
|
|
# Issue 1402: the PyGILState_Ensure / _Release functions may be called
|
|
# very late on python exit: on deallocation of a running thread for
|
|
# example.
|
|
try:
|
|
import ctypes
|
|
except ImportError:
|
|
if verbose:
|
|
print("test_finalize_with_runnning_thread can't import ctypes")
|
|
return # can't do anything
|
|
|
|
import subprocess
|
|
rc = subprocess.call([sys.executable, "-c", """if 1:
|
|
import ctypes, sys, time, _thread
|
|
|
|
# This lock is used as a simple event variable.
|
|
ready = _thread.allocate_lock()
|
|
ready.acquire()
|
|
|
|
# Module globals are cleared before __del__ is run
|
|
# So we save the functions in class dict
|
|
class C:
|
|
ensure = ctypes.pythonapi.PyGILState_Ensure
|
|
release = ctypes.pythonapi.PyGILState_Release
|
|
def __del__(self):
|
|
state = self.ensure()
|
|
self.release(state)
|
|
|
|
def waitingThread():
|
|
x = C()
|
|
ready.release()
|
|
time.sleep(100)
|
|
|
|
_thread.start_new_thread(waitingThread, ())
|
|
ready.acquire() # Be sure the other thread is waiting.
|
|
sys.exit(42)
|
|
"""])
|
|
self.assertEqual(rc, 42)
|
|
|
|
def test_finalize_with_trace(self):
|
|
# Issue1733757
|
|
# Avoid a deadlock when sys.settrace steps into threading._shutdown
|
|
import subprocess
|
|
rc = subprocess.call([sys.executable, "-c", """if 1:
|
|
import sys, threading
|
|
|
|
# A deadlock-killer, to prevent the
|
|
# testsuite to hang forever
|
|
def killer():
|
|
import os, time
|
|
time.sleep(2)
|
|
print('program blocked; aborting')
|
|
os._exit(2)
|
|
t = threading.Thread(target=killer)
|
|
t.daemon = True
|
|
t.start()
|
|
|
|
# This is the trace function
|
|
def func(frame, event, arg):
|
|
threading.current_thread()
|
|
return func
|
|
|
|
sys.settrace(func)
|
|
"""])
|
|
self.failIf(rc == 2, "interpreted was blocked")
|
|
self.failUnless(rc == 0, "Unexpected error")
|
|
|
|
|
|
def test_enumerate_after_join(self):
|
|
# Try hard to trigger #1703448: a thread is still returned in
|
|
# threading.enumerate() after it has been join()ed.
|
|
enum = threading.enumerate
|
|
old_interval = sys.getcheckinterval()
|
|
try:
|
|
for i in range(1, 100):
|
|
# Try a couple times at each thread-switching interval
|
|
# to get more interleavings.
|
|
sys.setcheckinterval(i // 5)
|
|
t = threading.Thread(target=lambda: None)
|
|
t.start()
|
|
t.join()
|
|
l = enum()
|
|
self.assertFalse(t in l,
|
|
"#1703448 triggered after %d trials: %s" % (i, l))
|
|
finally:
|
|
sys.setcheckinterval(old_interval)
|
|
|
|
def test_no_refcycle_through_target(self):
|
|
class RunSelfFunction(object):
|
|
def __init__(self, should_raise):
|
|
# The links in this refcycle from Thread back to self
|
|
# should be cleaned up when the thread completes.
|
|
self.should_raise = should_raise
|
|
self.thread = threading.Thread(target=self._run,
|
|
args=(self,),
|
|
kwargs={'yet_another':self})
|
|
self.thread.start()
|
|
|
|
def _run(self, other_ref, yet_another):
|
|
if self.should_raise:
|
|
raise SystemExit
|
|
|
|
cyclic_object = RunSelfFunction(should_raise=False)
|
|
weak_cyclic_object = weakref.ref(cyclic_object)
|
|
cyclic_object.thread.join()
|
|
del cyclic_object
|
|
self.assertEquals(None, weak_cyclic_object(),
|
|
msg=('%d references still around' %
|
|
sys.getrefcount(weak_cyclic_object())))
|
|
|
|
raising_cyclic_object = RunSelfFunction(should_raise=True)
|
|
weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
|
|
raising_cyclic_object.thread.join()
|
|
del raising_cyclic_object
|
|
self.assertEquals(None, weak_raising_cyclic_object(),
|
|
msg=('%d references still around' %
|
|
sys.getrefcount(weak_raising_cyclic_object())))
|
|
|
|
def test_old_threading_api(self):
|
|
# Just a quick sanity check to make sure the old method names are
|
|
# still present
|
|
t = threading.Thread()
|
|
t.isDaemon()
|
|
t.setDaemon(True)
|
|
t.getName()
|
|
t.setName("name")
|
|
t.isAlive()
|
|
e = threading.Event()
|
|
e.isSet()
|
|
threading.activeCount()
|
|
|
|
|
|
class ThreadJoinOnShutdown(unittest.TestCase):
|
|
|
|
def _run_and_join(self, script):
|
|
script = """if 1:
|
|
import sys, os, time, threading
|
|
|
|
# a thread, which waits for the main program to terminate
|
|
def joiningfunc(mainthread):
|
|
mainthread.join()
|
|
print('end of thread')
|
|
# stdout is fully buffered because not a tty, we have to flush
|
|
# before exit.
|
|
sys.stdout.flush()
|
|
\n""" + script
|
|
|
|
import subprocess
|
|
p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
|
|
rc = p.wait()
|
|
data = p.stdout.read().decode().replace('\r', '')
|
|
self.assertEqual(data, "end of main\nend of thread\n")
|
|
self.failIf(rc == 2, "interpreter was blocked")
|
|
self.failUnless(rc == 0, "Unexpected error")
|
|
|
|
def test_1_join_on_shutdown(self):
|
|
# The usual case: on exit, wait for a non-daemon thread
|
|
script = """if 1:
|
|
import os
|
|
t = threading.Thread(target=joiningfunc,
|
|
args=(threading.current_thread(),))
|
|
t.start()
|
|
time.sleep(0.1)
|
|
print('end of main')
|
|
"""
|
|
self._run_and_join(script)
|
|
|
|
|
|
def test_2_join_in_forked_process(self):
|
|
# Like the test above, but from a forked interpreter
|
|
import os
|
|
if not hasattr(os, 'fork'):
|
|
return
|
|
script = """if 1:
|
|
childpid = os.fork()
|
|
if childpid != 0:
|
|
os.waitpid(childpid, 0)
|
|
sys.exit(0)
|
|
|
|
t = threading.Thread(target=joiningfunc,
|
|
args=(threading.current_thread(),))
|
|
t.start()
|
|
print('end of main')
|
|
"""
|
|
self._run_and_join(script)
|
|
|
|
def test_3_join_in_forked_from_thread(self):
|
|
# Like the test above, but fork() was called from a worker thread
|
|
# In the forked process, the main Thread object must be marked as stopped.
|
|
import os
|
|
if not hasattr(os, 'fork'):
|
|
return
|
|
# Skip platforms with known problems forking from a worker thread.
|
|
# See http://bugs.python.org/issue3863.
|
|
if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
|
|
print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread'
|
|
' due to known OS bugs on'), sys.platform
|
|
return
|
|
script = """if 1:
|
|
main_thread = threading.current_thread()
|
|
def worker():
|
|
childpid = os.fork()
|
|
if childpid != 0:
|
|
os.waitpid(childpid, 0)
|
|
sys.exit(0)
|
|
|
|
t = threading.Thread(target=joiningfunc,
|
|
args=(main_thread,))
|
|
print('end of main')
|
|
t.start()
|
|
t.join() # Should not block: main_thread is already stopped
|
|
|
|
w = threading.Thread(target=worker)
|
|
w.start()
|
|
"""
|
|
self._run_and_join(script)
|
|
|
|
|
|
class ThreadingExceptionTests(unittest.TestCase):
|
|
# A RuntimeError should be raised if Thread.start() is called
|
|
# multiple times.
|
|
def test_start_thread_again(self):
|
|
thread = threading.Thread()
|
|
thread.start()
|
|
self.assertRaises(RuntimeError, thread.start)
|
|
|
|
def test_releasing_unacquired_rlock(self):
|
|
rlock = threading.RLock()
|
|
self.assertRaises(RuntimeError, rlock.release)
|
|
|
|
def test_waiting_on_unacquired_condition(self):
|
|
cond = threading.Condition()
|
|
self.assertRaises(RuntimeError, cond.wait)
|
|
|
|
def test_notify_on_unacquired_condition(self):
|
|
cond = threading.Condition()
|
|
self.assertRaises(RuntimeError, cond.notify)
|
|
|
|
def test_semaphore_with_negative_value(self):
|
|
self.assertRaises(ValueError, threading.Semaphore, value = -1)
|
|
self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
|
|
|
|
def test_joining_current_thread(self):
|
|
current_thread = threading.current_thread()
|
|
self.assertRaises(RuntimeError, current_thread.join);
|
|
|
|
def test_joining_inactive_thread(self):
|
|
thread = threading.Thread()
|
|
self.assertRaises(RuntimeError, thread.join)
|
|
|
|
def test_daemonize_active_thread(self):
|
|
thread = threading.Thread()
|
|
thread.start()
|
|
self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
|
|
|
|
|
|
def test_main():
|
|
test.support.run_unittest(ThreadTests,
|
|
ThreadJoinOnShutdown,
|
|
ThreadingExceptionTests,
|
|
)
|
|
|
|
if __name__ == "__main__":
|
|
test_main()
|