blob: 8c1ecce2dda04ee102f9e589f2bca156a02236a7 [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
Gregory P. Smith8856dda2008-06-01 23:48:47 +00006import re
Collin Winter50b79ce2007-06-06 00:17:35 +00007import sys
Skip Montanaro4533f602001-08-20 20:28:48 +00008import threading
Tim Peters711906e2005-01-08 07:30:42 +00009import thread
Skip Montanaro4533f602001-08-20 20:28:48 +000010import time
Tim Peters84d54892005-01-08 06:03:17 +000011import unittest
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +000012import weakref
Skip Montanaro4533f602001-08-20 20:28:48 +000013
Tim Peters84d54892005-01-08 06:03:17 +000014# A trivial mutable counter.
15class Counter(object):
16 def __init__(self):
17 self.value = 0
18 def inc(self):
19 self.value += 1
20 def dec(self):
21 self.value -= 1
22 def get(self):
23 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000024
25class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000026 def __init__(self, name, testcase, sema, mutex, nrunning):
27 threading.Thread.__init__(self, name=name)
28 self.testcase = testcase
29 self.sema = sema
30 self.mutex = mutex
31 self.nrunning = nrunning
32
Skip Montanaro4533f602001-08-20 20:28:48 +000033 def run(self):
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000034 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000035 if verbose:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000036 print 'task %s will run for %.1f usec' % (
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000037 self.get_name(), delay * 1e6)
Tim Peters84d54892005-01-08 06:03:17 +000038
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000039 with self.sema:
40 with self.mutex:
41 self.nrunning.inc()
42 if verbose:
43 print self.nrunning.get(), 'tasks are running'
44 self.testcase.assert_(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000045
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000046 time.sleep(delay)
47 if verbose:
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000048 print 'task', self.get_name(), 'done'
Tim Peters84d54892005-01-08 06:03:17 +000049
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000050 with self.mutex:
51 self.nrunning.dec()
52 self.testcase.assert_(self.nrunning.get() >= 0)
53 if verbose:
54 print '%s is finished. %d tasks are running' % (
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000055 self.get_name(), self.nrunning.get())
Skip Montanaro4533f602001-08-20 20:28:48 +000056
Tim Peters84d54892005-01-08 06:03:17 +000057class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000058
Tim Peters84d54892005-01-08 06:03:17 +000059 # Create a bunch of threads, let each do some work, wait until all are
60 # done.
61 def test_various_ops(self):
62 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
63 # times about 1 second per clump).
64 NUMTASKS = 10
65
66 # no more than 3 of the 10 can run at once
67 sema = threading.BoundedSemaphore(value=3)
68 mutex = threading.RLock()
69 numrunning = Counter()
70
71 threads = []
72
73 for i in range(NUMTASKS):
74 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
75 threads.append(t)
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000076 self.failUnlessEqual(t.get_ident(), None)
Gregory P. Smith8856dda2008-06-01 23:48:47 +000077 self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000078 t.start()
79
80 if verbose:
81 print 'waiting for all tasks to complete'
82 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000083 t.join(NUMTASKS)
Benjamin Peterson0fbcf692008-06-11 17:27:50 +000084 self.assert_(not t.is_alive())
85 self.failIfEqual(t.get_ident(), 0)
Gregory P. Smith8856dda2008-06-01 23:48:47 +000086 self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000087 if verbose:
88 print 'all tasks done'
89 self.assertEqual(numrunning.get(), 0)
90
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +000091 # run with a small(ish) thread stack size (256kB)
Andrew MacIntyre92913322006-06-13 15:04:24 +000092 def test_various_ops_small_stack(self):
93 if verbose:
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +000094 print 'with 256kB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +000095 try:
96 threading.stack_size(262144)
97 except thread.error:
98 if verbose:
99 print 'platform does not support changing thread stack size'
100 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000101 self.test_various_ops()
102 threading.stack_size(0)
103
104 # run with a large thread stack size (1MB)
105 def test_various_ops_large_stack(self):
106 if verbose:
107 print 'with 1MB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000108 try:
109 threading.stack_size(0x100000)
110 except thread.error:
111 if verbose:
112 print 'platform does not support changing thread stack size'
113 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000114 self.test_various_ops()
115 threading.stack_size(0)
116
Tim Peters711906e2005-01-08 07:30:42 +0000117 def test_foreign_thread(self):
118 # Check that a "foreign" thread can use the threading module.
119 def f(mutex):
120 # Acquiring an RLock forces an entry for the foreign
121 # thread to get made in the threading._active map.
122 r = threading.RLock()
123 r.acquire()
124 r.release()
125 mutex.release()
126
127 mutex = threading.Lock()
128 mutex.acquire()
129 tid = thread.start_new_thread(f, (mutex,))
130 # Wait for the thread to finish.
131 mutex.acquire()
132 self.assert_(tid in threading._active)
133 self.assert_(isinstance(threading._active[tid],
134 threading._DummyThread))
135 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000136
Tim Peters4643c2f2006-08-10 22:45:34 +0000137 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
138 # exposed at the Python level. This test relies on ctypes to get at it.
139 def test_PyThreadState_SetAsyncExc(self):
140 try:
141 import ctypes
142 except ImportError:
143 if verbose:
144 print "test_PyThreadState_SetAsyncExc can't import ctypes"
145 return # can't do anything
146
147 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
148
149 class AsyncExc(Exception):
150 pass
151
152 exception = ctypes.py_object(AsyncExc)
153
154 # `worker_started` is set by the thread when it's inside a try/except
155 # block waiting to catch the asynchronously set AsyncExc exception.
156 # `worker_saw_exception` is set by the thread upon catching that
157 # exception.
158 worker_started = threading.Event()
159 worker_saw_exception = threading.Event()
160
161 class Worker(threading.Thread):
162 def run(self):
163 self.id = thread.get_ident()
164 self.finished = False
165
166 try:
167 while True:
168 worker_started.set()
169 time.sleep(0.1)
170 except AsyncExc:
171 self.finished = True
172 worker_saw_exception.set()
173
174 t = Worker()
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000175 t.set_daemon(True) # so if this fails, we don't hang Python at shutdown
Tim Peters08574772006-08-11 00:49:01 +0000176 t.start()
Tim Peters4643c2f2006-08-10 22:45:34 +0000177 if verbose:
178 print " started worker thread"
Tim Peters4643c2f2006-08-10 22:45:34 +0000179
180 # Try a thread id that doesn't make sense.
181 if verbose:
182 print " trying nonsensical thread id"
Tim Peters08574772006-08-11 00:49:01 +0000183 result = set_async_exc(ctypes.c_long(-1), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000184 self.assertEqual(result, 0) # no thread states modified
185
186 # Now raise an exception in the worker thread.
187 if verbose:
188 print " waiting for worker thread to get started"
189 worker_started.wait()
190 if verbose:
191 print " verifying worker hasn't exited"
192 self.assert_(not t.finished)
193 if verbose:
194 print " attempting to raise asynch exception in worker"
Tim Peters08574772006-08-11 00:49:01 +0000195 result = set_async_exc(ctypes.c_long(t.id), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000196 self.assertEqual(result, 1) # one thread state modified
197 if verbose:
198 print " waiting for worker to say it caught the exception"
199 worker_saw_exception.wait(timeout=10)
200 self.assert_(t.finished)
201 if verbose:
202 print " all OK -- joining worker"
203 if t.finished:
204 t.join()
205 # else the thread is still running, and we have no way to kill it
206
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000207 def test_finalize_runnning_thread(self):
208 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
209 # very late on python exit: on deallocation of a running thread for
210 # example.
211 try:
212 import ctypes
213 except ImportError:
214 if verbose:
215 print("test_finalize_with_runnning_thread can't import ctypes")
216 return # can't do anything
217
218 import subprocess
219 rc = subprocess.call([sys.executable, "-c", """if 1:
220 import ctypes, sys, time, thread
221
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000222 # This lock is used as a simple event variable.
223 ready = thread.allocate_lock()
224 ready.acquire()
225
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000226 # Module globals are cleared before __del__ is run
227 # So we save the functions in class dict
228 class C:
229 ensure = ctypes.pythonapi.PyGILState_Ensure
230 release = ctypes.pythonapi.PyGILState_Release
231 def __del__(self):
232 state = self.ensure()
233 self.release(state)
234
235 def waitingThread():
236 x = C()
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000237 ready.release()
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000238 time.sleep(100)
239
240 thread.start_new_thread(waitingThread, ())
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000241 ready.acquire() # Be sure the other thread is waiting.
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000242 sys.exit(42)
243 """])
244 self.assertEqual(rc, 42)
245
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000246 def test_finalize_with_trace(self):
247 # Issue1733757
248 # Avoid a deadlock when sys.settrace steps into threading._shutdown
249 import subprocess
250 rc = subprocess.call([sys.executable, "-c", """if 1:
251 import sys, threading
252
253 # A deadlock-killer, to prevent the
254 # testsuite to hang forever
255 def killer():
256 import os, time
257 time.sleep(2)
258 print 'program blocked; aborting'
259 os._exit(2)
260 t = threading.Thread(target=killer)
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000261 t.set_daemon(True)
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000262 t.start()
263
264 # This is the trace function
265 def func(frame, event, arg):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000266 threading.current_thread()
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000267 return func
268
269 sys.settrace(func)
270 """])
271 self.failIf(rc == 2, "interpreted was blocked")
272 self.failUnless(rc == 0, "Unexpected error")
273
274
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000275 def test_enumerate_after_join(self):
276 # Try hard to trigger #1703448: a thread is still returned in
277 # threading.enumerate() after it has been join()ed.
278 enum = threading.enumerate
279 old_interval = sys.getcheckinterval()
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000280 try:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000281 for i in xrange(1, 100):
282 # Try a couple times at each thread-switching interval
283 # to get more interleavings.
284 sys.setcheckinterval(i // 5)
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000285 t = threading.Thread(target=lambda: None)
286 t.start()
287 t.join()
288 l = enum()
289 self.assertFalse(t in l,
290 "#1703448 triggered after %d trials: %s" % (i, l))
291 finally:
292 sys.setcheckinterval(old_interval)
293
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000294 def test_no_refcycle_through_target(self):
295 class RunSelfFunction(object):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000296 def __init__(self, should_raise):
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000297 # The links in this refcycle from Thread back to self
298 # should be cleaned up when the thread completes.
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000299 self.should_raise = should_raise
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000300 self.thread = threading.Thread(target=self._run,
301 args=(self,),
302 kwargs={'yet_another':self})
303 self.thread.start()
304
305 def _run(self, other_ref, yet_another):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000306 if self.should_raise:
307 raise SystemExit
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000308
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000309 cyclic_object = RunSelfFunction(should_raise=False)
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000310 weak_cyclic_object = weakref.ref(cyclic_object)
311 cyclic_object.thread.join()
312 del cyclic_object
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000313 self.assertEquals(None, weak_cyclic_object(),
314 msg=('%d references still around' %
315 sys.getrefcount(weak_cyclic_object())))
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000316
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000317 raising_cyclic_object = RunSelfFunction(should_raise=True)
318 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
319 raising_cyclic_object.thread.join()
320 del raising_cyclic_object
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000321 self.assertEquals(None, weak_raising_cyclic_object(),
322 msg=('%d references still around' %
323 sys.getrefcount(weak_raising_cyclic_object())))
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000324
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000325
Jesse Noller5e62ca42008-07-16 20:03:47 +0000326class ThreadJoinOnShutdown(unittest.TestCase):
327
328 def _run_and_join(self, script):
329 script = """if 1:
330 import sys, os, time, threading
331
332 # a thread, which waits for the main program to terminate
333 def joiningfunc(mainthread):
334 mainthread.join()
335 print 'end of thread'
336 \n""" + script
337
338 import subprocess
339 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
340 rc = p.wait()
341 self.assertEqual(p.stdout.read(), "end of main\nend of thread\n")
342 self.failIf(rc == 2, "interpreter was blocked")
343 self.failUnless(rc == 0, "Unexpected error")
344
345 def test_1_join_on_shutdown(self):
346 # The usual case: on exit, wait for a non-daemon thread
347 script = """if 1:
348 import os
349 t = threading.Thread(target=joiningfunc,
350 args=(threading.current_thread(),))
351 t.start()
352 time.sleep(0.1)
353 print 'end of main'
354 """
355 self._run_and_join(script)
356
357
358 def test_2_join_in_forked_process(self):
359 # Like the test above, but from a forked interpreter
360 import os
361 if not hasattr(os, 'fork'):
362 return
363 script = """if 1:
364 childpid = os.fork()
365 if childpid != 0:
366 os.waitpid(childpid, 0)
367 sys.exit(0)
368
369 t = threading.Thread(target=joiningfunc,
370 args=(threading.current_thread(),))
371 t.start()
372 print 'end of main'
373 """
374 self._run_and_join(script)
375
376 def test_3_join_in_forked_from_thread(self):
377 # Like the test above, but fork() was called from a worker thread
378 # In the forked process, the main Thread object must be marked as stopped.
379 import os
380 if not hasattr(os, 'fork'):
381 return
382 script = """if 1:
383 main_thread = threading.current_thread()
384 def worker():
385 childpid = os.fork()
386 if childpid != 0:
387 os.waitpid(childpid, 0)
388 sys.exit(0)
389
390 t = threading.Thread(target=joiningfunc,
391 args=(main_thread,))
392 print 'end of main'
393 t.start()
394 t.join() # Should not block: main_thread is already stopped
395
396 w = threading.Thread(target=worker)
397 w.start()
398 """
399 self._run_and_join(script)
400
401
Collin Winter50b79ce2007-06-06 00:17:35 +0000402class ThreadingExceptionTests(unittest.TestCase):
403 # A RuntimeError should be raised if Thread.start() is called
404 # multiple times.
405 def test_start_thread_again(self):
406 thread = threading.Thread()
407 thread.start()
408 self.assertRaises(RuntimeError, thread.start)
409
410 def test_releasing_unacquired_rlock(self):
411 rlock = threading.RLock()
412 self.assertRaises(RuntimeError, rlock.release)
413
414 def test_waiting_on_unacquired_condition(self):
415 cond = threading.Condition()
416 self.assertRaises(RuntimeError, cond.wait)
417
418 def test_notify_on_unacquired_condition(self):
419 cond = threading.Condition()
420 self.assertRaises(RuntimeError, cond.notify)
421
422 def test_semaphore_with_negative_value(self):
423 self.assertRaises(ValueError, threading.Semaphore, value = -1)
424 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxint)
425
426 def test_joining_current_thread(self):
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000427 current_thread = threading.current_thread()
428 self.assertRaises(RuntimeError, current_thread.join);
Collin Winter50b79ce2007-06-06 00:17:35 +0000429
430 def test_joining_inactive_thread(self):
431 thread = threading.Thread()
432 self.assertRaises(RuntimeError, thread.join)
433
434 def test_daemonize_active_thread(self):
435 thread = threading.Thread()
436 thread.start()
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000437 self.assertRaises(RuntimeError, thread.set_daemon, True)
Collin Winter50b79ce2007-06-06 00:17:35 +0000438
439
Tim Peters84d54892005-01-08 06:03:17 +0000440def test_main():
Collin Winter50b79ce2007-06-06 00:17:35 +0000441 test.test_support.run_unittest(ThreadTests,
Jesse Noller5e62ca42008-07-16 20:03:47 +0000442 ThreadJoinOnShutdown,
443 ThreadingExceptionTests,
444 )
Tim Peters84d54892005-01-08 06:03:17 +0000445
446if __name__ == "__main__":
447 test_main()