blob: 91f5a8b2df665ceb40aaf2675b45b2f1ea9f6729 [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
Tim Peters84d54892005-01-08 06:03:17 +00003import test.test_support
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test.test_support import verbose
Skip Montanaro4533f602001-08-20 20:28:48 +00005import random
Collin Winter50b79ce2007-06-06 00:17:35 +00006import sys
Skip Montanaro4533f602001-08-20 20:28:48 +00007import threading
Tim Peters711906e2005-01-08 07:30:42 +00008import thread
Skip Montanaro4533f602001-08-20 20:28:48 +00009import time
Tim Peters84d54892005-01-08 06:03:17 +000010import unittest
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +000011import weakref
Skip Montanaro4533f602001-08-20 20:28:48 +000012
Tim Peters84d54892005-01-08 06:03:17 +000013# A trivial mutable counter.
14class Counter(object):
15 def __init__(self):
16 self.value = 0
17 def inc(self):
18 self.value += 1
19 def dec(self):
20 self.value -= 1
21 def get(self):
22 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000023
24class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000025 def __init__(self, name, testcase, sema, mutex, nrunning):
26 threading.Thread.__init__(self, name=name)
27 self.testcase = testcase
28 self.sema = sema
29 self.mutex = mutex
30 self.nrunning = nrunning
31
Skip Montanaro4533f602001-08-20 20:28:48 +000032 def run(self):
Tim Peters02035bc2001-08-20 21:45:19 +000033 delay = random.random() * 2
Skip Montanaro4533f602001-08-20 20:28:48 +000034 if verbose:
Tim Peters02035bc2001-08-20 21:45:19 +000035 print 'task', self.getName(), 'will run for', delay, 'sec'
Tim Peters84d54892005-01-08 06:03:17 +000036
37 self.sema.acquire()
38
39 self.mutex.acquire()
40 self.nrunning.inc()
Skip Montanaro4533f602001-08-20 20:28:48 +000041 if verbose:
Tim Peters84d54892005-01-08 06:03:17 +000042 print self.nrunning.get(), 'tasks are running'
43 self.testcase.assert_(self.nrunning.get() <= 3)
44 self.mutex.release()
45
Skip Montanaro4533f602001-08-20 20:28:48 +000046 time.sleep(delay)
47 if verbose:
48 print 'task', self.getName(), 'done'
Tim Peters84d54892005-01-08 06:03:17 +000049
50 self.mutex.acquire()
51 self.nrunning.dec()
52 self.testcase.assert_(self.nrunning.get() >= 0)
Skip Montanaro4533f602001-08-20 20:28:48 +000053 if verbose:
Tim Peters84d54892005-01-08 06:03:17 +000054 print self.getName(), 'is finished.', self.nrunning.get(), \
55 'tasks are running'
56 self.mutex.release()
Skip Montanaro4533f602001-08-20 20:28:48 +000057
Tim Peters84d54892005-01-08 06:03:17 +000058 self.sema.release()
Skip Montanaro4533f602001-08-20 20:28:48 +000059
Tim Peters84d54892005-01-08 06:03:17 +000060class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000061
Tim Peters84d54892005-01-08 06:03:17 +000062 # Create a bunch of threads, let each do some work, wait until all are
63 # done.
64 def test_various_ops(self):
65 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
66 # times about 1 second per clump).
67 NUMTASKS = 10
68
69 # no more than 3 of the 10 can run at once
70 sema = threading.BoundedSemaphore(value=3)
71 mutex = threading.RLock()
72 numrunning = Counter()
73
74 threads = []
75
76 for i in range(NUMTASKS):
77 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
78 threads.append(t)
79 t.start()
80
81 if verbose:
82 print 'waiting for all tasks to complete'
83 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000084 t.join(NUMTASKS)
85 self.assert_(not t.isAlive())
Tim Peters84d54892005-01-08 06:03:17 +000086 if verbose:
87 print 'all tasks done'
88 self.assertEqual(numrunning.get(), 0)
89
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +000090 # run with a small(ish) thread stack size (256kB)
Andrew MacIntyre92913322006-06-13 15:04:24 +000091 def test_various_ops_small_stack(self):
92 if verbose:
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +000093 print 'with 256kB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +000094 try:
95 threading.stack_size(262144)
96 except thread.error:
97 if verbose:
98 print 'platform does not support changing thread stack size'
99 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000100 self.test_various_ops()
101 threading.stack_size(0)
102
103 # run with a large thread stack size (1MB)
104 def test_various_ops_large_stack(self):
105 if verbose:
106 print 'with 1MB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000107 try:
108 threading.stack_size(0x100000)
109 except thread.error:
110 if verbose:
111 print 'platform does not support changing thread stack size'
112 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000113 self.test_various_ops()
114 threading.stack_size(0)
115
Tim Peters711906e2005-01-08 07:30:42 +0000116 def test_foreign_thread(self):
117 # Check that a "foreign" thread can use the threading module.
118 def f(mutex):
119 # Acquiring an RLock forces an entry for the foreign
120 # thread to get made in the threading._active map.
121 r = threading.RLock()
122 r.acquire()
123 r.release()
124 mutex.release()
125
126 mutex = threading.Lock()
127 mutex.acquire()
128 tid = thread.start_new_thread(f, (mutex,))
129 # Wait for the thread to finish.
130 mutex.acquire()
131 self.assert_(tid in threading._active)
132 self.assert_(isinstance(threading._active[tid],
133 threading._DummyThread))
134 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000135
Tim Peters4643c2f2006-08-10 22:45:34 +0000136 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
137 # exposed at the Python level. This test relies on ctypes to get at it.
138 def test_PyThreadState_SetAsyncExc(self):
139 try:
140 import ctypes
141 except ImportError:
142 if verbose:
143 print "test_PyThreadState_SetAsyncExc can't import ctypes"
144 return # can't do anything
145
146 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
147
148 class AsyncExc(Exception):
149 pass
150
151 exception = ctypes.py_object(AsyncExc)
152
153 # `worker_started` is set by the thread when it's inside a try/except
154 # block waiting to catch the asynchronously set AsyncExc exception.
155 # `worker_saw_exception` is set by the thread upon catching that
156 # exception.
157 worker_started = threading.Event()
158 worker_saw_exception = threading.Event()
159
160 class Worker(threading.Thread):
161 def run(self):
162 self.id = thread.get_ident()
163 self.finished = False
164
165 try:
166 while True:
167 worker_started.set()
168 time.sleep(0.1)
169 except AsyncExc:
170 self.finished = True
171 worker_saw_exception.set()
172
173 t = Worker()
Tim Peters08574772006-08-11 00:49:01 +0000174 t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
175 t.start()
Tim Peters4643c2f2006-08-10 22:45:34 +0000176 if verbose:
177 print " started worker thread"
Tim Peters4643c2f2006-08-10 22:45:34 +0000178
179 # Try a thread id that doesn't make sense.
180 if verbose:
181 print " trying nonsensical thread id"
Tim Peters08574772006-08-11 00:49:01 +0000182 result = set_async_exc(ctypes.c_long(-1), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000183 self.assertEqual(result, 0) # no thread states modified
184
185 # Now raise an exception in the worker thread.
186 if verbose:
187 print " waiting for worker thread to get started"
188 worker_started.wait()
189 if verbose:
190 print " verifying worker hasn't exited"
191 self.assert_(not t.finished)
192 if verbose:
193 print " attempting to raise asynch exception in worker"
Tim Peters08574772006-08-11 00:49:01 +0000194 result = set_async_exc(ctypes.c_long(t.id), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000195 self.assertEqual(result, 1) # one thread state modified
196 if verbose:
197 print " waiting for worker to say it caught the exception"
198 worker_saw_exception.wait(timeout=10)
199 self.assert_(t.finished)
200 if verbose:
201 print " all OK -- joining worker"
202 if t.finished:
203 t.join()
204 # else the thread is still running, and we have no way to kill it
205
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000206 def test_finalize_runnning_thread(self):
207 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
208 # very late on python exit: on deallocation of a running thread for
209 # example.
210 try:
211 import ctypes
212 except ImportError:
213 if verbose:
214 print("test_finalize_with_runnning_thread can't import ctypes")
215 return # can't do anything
216
217 import subprocess
218 rc = subprocess.call([sys.executable, "-c", """if 1:
219 import ctypes, sys, time, thread
220
221 # Module globals are cleared before __del__ is run
222 # So we save the functions in class dict
223 class C:
224 ensure = ctypes.pythonapi.PyGILState_Ensure
225 release = ctypes.pythonapi.PyGILState_Release
226 def __del__(self):
227 state = self.ensure()
228 self.release(state)
229
230 def waitingThread():
231 x = C()
232 time.sleep(100)
233
234 thread.start_new_thread(waitingThread, ())
235 time.sleep(1) # be sure the other thread is waiting
236 sys.exit(42)
237 """])
238 self.assertEqual(rc, 42)
239
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000240 def test_enumerate_after_join(self):
241 # Try hard to trigger #1703448: a thread is still returned in
242 # threading.enumerate() after it has been join()ed.
243 enum = threading.enumerate
244 old_interval = sys.getcheckinterval()
245 sys.setcheckinterval(1)
246 try:
247 for i in xrange(1, 1000):
248 t = threading.Thread(target=lambda: None)
249 t.start()
250 t.join()
251 l = enum()
252 self.assertFalse(t in l,
253 "#1703448 triggered after %d trials: %s" % (i, l))
254 finally:
255 sys.setcheckinterval(old_interval)
256
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000257 def test_no_refcycle_through_target(self):
258 class RunSelfFunction(object):
259 def __init__(self):
260 # The links in this refcycle from Thread back to self
261 # should be cleaned up when the thread completes.
262 self.thread = threading.Thread(target=self._run,
263 args=(self,),
264 kwargs={'yet_another':self})
265 self.thread.start()
266
267 def _run(self, other_ref, yet_another):
268 pass
269
270 cyclic_object = RunSelfFunction()
271 weak_cyclic_object = weakref.ref(cyclic_object)
272 cyclic_object.thread.join()
273 del cyclic_object
274 self.assertEquals(None, weak_cyclic_object())
275
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000276
Collin Winter50b79ce2007-06-06 00:17:35 +0000277class ThreadingExceptionTests(unittest.TestCase):
278 # A RuntimeError should be raised if Thread.start() is called
279 # multiple times.
280 def test_start_thread_again(self):
281 thread = threading.Thread()
282 thread.start()
283 self.assertRaises(RuntimeError, thread.start)
284
285 def test_releasing_unacquired_rlock(self):
286 rlock = threading.RLock()
287 self.assertRaises(RuntimeError, rlock.release)
288
289 def test_waiting_on_unacquired_condition(self):
290 cond = threading.Condition()
291 self.assertRaises(RuntimeError, cond.wait)
292
293 def test_notify_on_unacquired_condition(self):
294 cond = threading.Condition()
295 self.assertRaises(RuntimeError, cond.notify)
296
297 def test_semaphore_with_negative_value(self):
298 self.assertRaises(ValueError, threading.Semaphore, value = -1)
299 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxint)
300
301 def test_joining_current_thread(self):
302 currentThread = threading.currentThread()
303 self.assertRaises(RuntimeError, currentThread.join);
304
305 def test_joining_inactive_thread(self):
306 thread = threading.Thread()
307 self.assertRaises(RuntimeError, thread.join)
308
309 def test_daemonize_active_thread(self):
310 thread = threading.Thread()
311 thread.start()
312 self.assertRaises(RuntimeError, thread.setDaemon, True)
313
314
Tim Peters84d54892005-01-08 06:03:17 +0000315def test_main():
Collin Winter50b79ce2007-06-06 00:17:35 +0000316 test.test_support.run_unittest(ThreadTests,
317 ThreadingExceptionTests)
Tim Peters84d54892005-01-08 06:03:17 +0000318
319if __name__ == "__main__":
320 test_main()