blob: 30aa9d578675a6636b6b1265259c59f215cda2ab [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):
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000033 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000034 if verbose:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000035 print 'task %s will run for %.1f usec' % (
36 self.getName(), delay * 1e6)
Tim Peters84d54892005-01-08 06:03:17 +000037
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000038 with self.sema:
39 with self.mutex:
40 self.nrunning.inc()
41 if verbose:
42 print self.nrunning.get(), 'tasks are running'
43 self.testcase.assert_(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000044
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000045 time.sleep(delay)
46 if verbose:
47 print 'task', self.getName(), 'done'
Tim Peters84d54892005-01-08 06:03:17 +000048
Jeffrey Yasskin510eab52008-03-21 18:48:04 +000049 with self.mutex:
50 self.nrunning.dec()
51 self.testcase.assert_(self.nrunning.get() >= 0)
52 if verbose:
53 print '%s is finished. %d tasks are running' % (
54 self.getName(), self.nrunning.get())
Skip Montanaro4533f602001-08-20 20:28:48 +000055
Tim Peters84d54892005-01-08 06:03:17 +000056class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000057
Tim Peters84d54892005-01-08 06:03:17 +000058 # Create a bunch of threads, let each do some work, wait until all are
59 # done.
60 def test_various_ops(self):
61 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
62 # times about 1 second per clump).
63 NUMTASKS = 10
64
65 # no more than 3 of the 10 can run at once
66 sema = threading.BoundedSemaphore(value=3)
67 mutex = threading.RLock()
68 numrunning = Counter()
69
70 threads = []
71
72 for i in range(NUMTASKS):
73 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
74 threads.append(t)
75 t.start()
76
77 if verbose:
78 print 'waiting for all tasks to complete'
79 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000080 t.join(NUMTASKS)
81 self.assert_(not t.isAlive())
Tim Peters84d54892005-01-08 06:03:17 +000082 if verbose:
83 print 'all tasks done'
84 self.assertEqual(numrunning.get(), 0)
85
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +000086 # run with a small(ish) thread stack size (256kB)
Andrew MacIntyre92913322006-06-13 15:04:24 +000087 def test_various_ops_small_stack(self):
88 if verbose:
Andrew MacIntyre93e3ecb2006-06-13 19:02:35 +000089 print 'with 256kB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +000090 try:
91 threading.stack_size(262144)
92 except thread.error:
93 if verbose:
94 print 'platform does not support changing thread stack size'
95 return
Andrew MacIntyre92913322006-06-13 15:04:24 +000096 self.test_various_ops()
97 threading.stack_size(0)
98
99 # run with a large thread stack size (1MB)
100 def test_various_ops_large_stack(self):
101 if verbose:
102 print 'with 1MB thread stack size...'
Andrew MacIntyre16ee33a2006-08-06 12:37:03 +0000103 try:
104 threading.stack_size(0x100000)
105 except thread.error:
106 if verbose:
107 print 'platform does not support changing thread stack size'
108 return
Andrew MacIntyre92913322006-06-13 15:04:24 +0000109 self.test_various_ops()
110 threading.stack_size(0)
111
Tim Peters711906e2005-01-08 07:30:42 +0000112 def test_foreign_thread(self):
113 # Check that a "foreign" thread can use the threading module.
114 def f(mutex):
115 # Acquiring an RLock forces an entry for the foreign
116 # thread to get made in the threading._active map.
117 r = threading.RLock()
118 r.acquire()
119 r.release()
120 mutex.release()
121
122 mutex = threading.Lock()
123 mutex.acquire()
124 tid = thread.start_new_thread(f, (mutex,))
125 # Wait for the thread to finish.
126 mutex.acquire()
127 self.assert_(tid in threading._active)
128 self.assert_(isinstance(threading._active[tid],
129 threading._DummyThread))
130 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000131
Tim Peters4643c2f2006-08-10 22:45:34 +0000132 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
133 # exposed at the Python level. This test relies on ctypes to get at it.
134 def test_PyThreadState_SetAsyncExc(self):
135 try:
136 import ctypes
137 except ImportError:
138 if verbose:
139 print "test_PyThreadState_SetAsyncExc can't import ctypes"
140 return # can't do anything
141
142 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
143
144 class AsyncExc(Exception):
145 pass
146
147 exception = ctypes.py_object(AsyncExc)
148
149 # `worker_started` is set by the thread when it's inside a try/except
150 # block waiting to catch the asynchronously set AsyncExc exception.
151 # `worker_saw_exception` is set by the thread upon catching that
152 # exception.
153 worker_started = threading.Event()
154 worker_saw_exception = threading.Event()
155
156 class Worker(threading.Thread):
157 def run(self):
158 self.id = thread.get_ident()
159 self.finished = False
160
161 try:
162 while True:
163 worker_started.set()
164 time.sleep(0.1)
165 except AsyncExc:
166 self.finished = True
167 worker_saw_exception.set()
168
169 t = Worker()
Tim Peters08574772006-08-11 00:49:01 +0000170 t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
171 t.start()
Tim Peters4643c2f2006-08-10 22:45:34 +0000172 if verbose:
173 print " started worker thread"
Tim Peters4643c2f2006-08-10 22:45:34 +0000174
175 # Try a thread id that doesn't make sense.
176 if verbose:
177 print " trying nonsensical thread id"
Tim Peters08574772006-08-11 00:49:01 +0000178 result = set_async_exc(ctypes.c_long(-1), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000179 self.assertEqual(result, 0) # no thread states modified
180
181 # Now raise an exception in the worker thread.
182 if verbose:
183 print " waiting for worker thread to get started"
184 worker_started.wait()
185 if verbose:
186 print " verifying worker hasn't exited"
187 self.assert_(not t.finished)
188 if verbose:
189 print " attempting to raise asynch exception in worker"
Tim Peters08574772006-08-11 00:49:01 +0000190 result = set_async_exc(ctypes.c_long(t.id), exception)
Tim Peters4643c2f2006-08-10 22:45:34 +0000191 self.assertEqual(result, 1) # one thread state modified
192 if verbose:
193 print " waiting for worker to say it caught the exception"
194 worker_saw_exception.wait(timeout=10)
195 self.assert_(t.finished)
196 if verbose:
197 print " all OK -- joining worker"
198 if t.finished:
199 t.join()
200 # else the thread is still running, and we have no way to kill it
201
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000202 def test_finalize_runnning_thread(self):
203 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
204 # very late on python exit: on deallocation of a running thread for
205 # example.
206 try:
207 import ctypes
208 except ImportError:
209 if verbose:
210 print("test_finalize_with_runnning_thread can't import ctypes")
211 return # can't do anything
212
213 import subprocess
214 rc = subprocess.call([sys.executable, "-c", """if 1:
215 import ctypes, sys, time, thread
216
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000217 # This lock is used as a simple event variable.
218 ready = thread.allocate_lock()
219 ready.acquire()
220
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000221 # 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()
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000232 ready.release()
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000233 time.sleep(100)
234
235 thread.start_new_thread(waitingThread, ())
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000236 ready.acquire() # Be sure the other thread is waiting.
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000237 sys.exit(42)
238 """])
239 self.assertEqual(rc, 42)
240
Amaury Forgeot d'Arcd7a26512008-04-03 23:07:55 +0000241 def test_finalize_with_trace(self):
242 # Issue1733757
243 # Avoid a deadlock when sys.settrace steps into threading._shutdown
244 import subprocess
245 rc = subprocess.call([sys.executable, "-c", """if 1:
246 import sys, threading
247
248 # A deadlock-killer, to prevent the
249 # testsuite to hang forever
250 def killer():
251 import os, time
252 time.sleep(2)
253 print 'program blocked; aborting'
254 os._exit(2)
255 t = threading.Thread(target=killer)
256 t.setDaemon(True)
257 t.start()
258
259 # This is the trace function
260 def func(frame, event, arg):
261 threading.currentThread()
262 return func
263
264 sys.settrace(func)
265 """])
266 self.failIf(rc == 2, "interpreted was blocked")
267 self.failUnless(rc == 0, "Unexpected error")
268
269
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000270 def test_enumerate_after_join(self):
271 # Try hard to trigger #1703448: a thread is still returned in
272 # threading.enumerate() after it has been join()ed.
273 enum = threading.enumerate
274 old_interval = sys.getcheckinterval()
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000275 try:
Jeffrey Yasskin510eab52008-03-21 18:48:04 +0000276 for i in xrange(1, 100):
277 # Try a couple times at each thread-switching interval
278 # to get more interleavings.
279 sys.setcheckinterval(i // 5)
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000280 t = threading.Thread(target=lambda: None)
281 t.start()
282 t.join()
283 l = enum()
284 self.assertFalse(t in l,
285 "#1703448 triggered after %d trials: %s" % (i, l))
286 finally:
287 sys.setcheckinterval(old_interval)
288
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000289 def test_no_refcycle_through_target(self):
290 class RunSelfFunction(object):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000291 def __init__(self, should_raise):
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000292 # The links in this refcycle from Thread back to self
293 # should be cleaned up when the thread completes.
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000294 self.should_raise = should_raise
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000295 self.thread = threading.Thread(target=self._run,
296 args=(self,),
297 kwargs={'yet_another':self})
298 self.thread.start()
299
300 def _run(self, other_ref, yet_another):
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000301 if self.should_raise:
302 raise SystemExit
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000303
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000304 cyclic_object = RunSelfFunction(should_raise=False)
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000305 weak_cyclic_object = weakref.ref(cyclic_object)
306 cyclic_object.thread.join()
307 del cyclic_object
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000308 self.assertEquals(None, weak_cyclic_object(),
309 msg=('%d references still around' %
310 sys.getrefcount(weak_cyclic_object())))
Jeffrey Yasskin3414ea92008-02-23 19:40:54 +0000311
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000312 raising_cyclic_object = RunSelfFunction(should_raise=True)
313 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
314 raising_cyclic_object.thread.join()
315 del raising_cyclic_object
Jeffrey Yasskin8b9091f2008-03-28 04:11:18 +0000316 self.assertEquals(None, weak_raising_cyclic_object(),
317 msg=('%d references still around' %
318 sys.getrefcount(weak_raising_cyclic_object())))
Jeffrey Yasskina885c152008-02-23 20:40:35 +0000319
Gregory P. Smith95cd5c02008-01-22 01:20:42 +0000320
Collin Winter50b79ce2007-06-06 00:17:35 +0000321class ThreadingExceptionTests(unittest.TestCase):
322 # A RuntimeError should be raised if Thread.start() is called
323 # multiple times.
324 def test_start_thread_again(self):
325 thread = threading.Thread()
326 thread.start()
327 self.assertRaises(RuntimeError, thread.start)
328
329 def test_releasing_unacquired_rlock(self):
330 rlock = threading.RLock()
331 self.assertRaises(RuntimeError, rlock.release)
332
333 def test_waiting_on_unacquired_condition(self):
334 cond = threading.Condition()
335 self.assertRaises(RuntimeError, cond.wait)
336
337 def test_notify_on_unacquired_condition(self):
338 cond = threading.Condition()
339 self.assertRaises(RuntimeError, cond.notify)
340
341 def test_semaphore_with_negative_value(self):
342 self.assertRaises(ValueError, threading.Semaphore, value = -1)
343 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxint)
344
345 def test_joining_current_thread(self):
346 currentThread = threading.currentThread()
347 self.assertRaises(RuntimeError, currentThread.join);
348
349 def test_joining_inactive_thread(self):
350 thread = threading.Thread()
351 self.assertRaises(RuntimeError, thread.join)
352
353 def test_daemonize_active_thread(self):
354 thread = threading.Thread()
355 thread.start()
356 self.assertRaises(RuntimeError, thread.setDaemon, True)
357
358
Tim Peters84d54892005-01-08 06:03:17 +0000359def test_main():
Collin Winter50b79ce2007-06-06 00:17:35 +0000360 test.test_support.run_unittest(ThreadTests,
361 ThreadingExceptionTests)
Tim Peters84d54892005-01-08 06:03:17 +0000362
363if __name__ == "__main__":
364 test_main()