blob: 15edb1b141da265ae8055b38c10356b181d4e305 [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003import test.support
4from test.support import verbose
Skip Montanaro4533f602001-08-20 20:28:48 +00005import random
Georg Brandl0c77a822008-06-10 16:37:50 +00006import re
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007import sys
Skip Montanaro4533f602001-08-20 20:28:48 +00008import threading
Georg Brandl2067bfd2008-05-25 13:05:15 +00009import _thread
Skip Montanaro4533f602001-08-20 20:28:48 +000010import time
Tim Peters84d54892005-01-08 06:03:17 +000011import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +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):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000034 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000035 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000036 print('task %s will run for %.1f usec' %
37 (self.getName(), delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000038
Christian Heimes4fbc72b2008-03-22 00:47:35 +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
Christian Heimes4fbc72b2008-03-22 00:47:35 +000046 time.sleep(delay)
47 if verbose:
48 print('task', self.getName(), 'done')
49 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' %
Jeffrey Yasskinca674122008-03-29 05:06:52 +000054 (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)
Georg Brandl0c77a822008-06-10 16:37:50 +000075 self.failUnlessEqual(t.getIdent(), None)
76 self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000077 t.start()
78
79 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000080 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000081 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000082 t.join(NUMTASKS)
83 self.assert_(not t.isAlive())
Georg Brandl0c77a822008-06-10 16:37:50 +000084 self.failIfEqual(t.getIdent(), 0)
85 self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000086 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000087 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000088 self.assertEqual(numrunning.get(), 0)
89
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090 # run with a small(ish) thread stack size (256kB)
91 def test_various_ops_small_stack(self):
92 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000093 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094 try:
95 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +000096 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000097 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000098 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099 return
100 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:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000106 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107 try:
108 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000109 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000110 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000111 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112 return
113 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()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000128 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000129 # 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
Thomas Wouters00ee7ba2006-08-21 19:07:27 +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:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000143 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000144 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):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000162 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000163 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()
174 t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
175 t.start()
176 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000177 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178
179 # Try a thread id that doesn't make sense.
180 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000181 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000182 result = set_async_exc(ctypes.c_long(-1), exception)
183 self.assertEqual(result, 0) # no thread states modified
184
185 # Now raise an exception in the worker thread.
186 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000187 print(" waiting for worker thread to get started")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000188 worker_started.wait()
189 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000190 print(" verifying worker hasn't exited")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000191 self.assert_(not t.finished)
192 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000193 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000194 result = set_async_exc(ctypes.c_long(t.id), exception)
195 self.assertEqual(result, 1) # one thread state modified
196 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000197 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000198 worker_saw_exception.wait(timeout=10)
199 self.assert_(t.finished)
200 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000201 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000202 if t.finished:
203 t.join()
204 # else the thread is still running, and we have no way to kill it
205
Christian Heimes7d2ff882007-11-30 14:35:04 +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:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000219 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000220
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000221 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000222 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000223 ready.acquire()
224
Christian Heimes7d2ff882007-11-30 14:35:04 +0000225 # Module globals are cleared before __del__ is run
226 # So we save the functions in class dict
227 class C:
228 ensure = ctypes.pythonapi.PyGILState_Ensure
229 release = ctypes.pythonapi.PyGILState_Release
230 def __del__(self):
231 state = self.ensure()
232 self.release(state)
233
234 def waitingThread():
235 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000236 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000237 time.sleep(100)
238
Georg Brandl2067bfd2008-05-25 13:05:15 +0000239 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000240 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000241 sys.exit(42)
242 """])
243 self.assertEqual(rc, 42)
244
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000245 def test_finalize_with_trace(self):
246 # Issue1733757
247 # Avoid a deadlock when sys.settrace steps into threading._shutdown
248 import subprocess
249 rc = subprocess.call([sys.executable, "-c", """if 1:
250 import sys, threading
251
252 # A deadlock-killer, to prevent the
253 # testsuite to hang forever
254 def killer():
255 import os, time
256 time.sleep(2)
257 print('program blocked; aborting')
258 os._exit(2)
259 t = threading.Thread(target=killer)
260 t.setDaemon(True)
261 t.start()
262
263 # This is the trace function
264 def func(frame, event, arg):
265 threading.currentThread()
266 return func
267
268 sys.settrace(func)
269 """])
270 self.failIf(rc == 2, "interpreted was blocked")
271 self.failUnless(rc == 0, "Unexpected error")
272
273
Christian Heimes1af737c2008-01-23 08:24:23 +0000274 def test_enumerate_after_join(self):
275 # Try hard to trigger #1703448: a thread is still returned in
276 # threading.enumerate() after it has been join()ed.
277 enum = threading.enumerate
278 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000279 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000280 for i in range(1, 100):
281 # Try a couple times at each thread-switching interval
282 # to get more interleavings.
283 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000284 t = threading.Thread(target=lambda: None)
285 t.start()
286 t.join()
287 l = enum()
288 self.assertFalse(t in l,
289 "#1703448 triggered after %d trials: %s" % (i, l))
290 finally:
291 sys.setcheckinterval(old_interval)
292
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000293 def test_no_refcycle_through_target(self):
294 class RunSelfFunction(object):
295 def __init__(self, should_raise):
296 # The links in this refcycle from Thread back to self
297 # should be cleaned up when the thread completes.
298 self.should_raise = should_raise
299 self.thread = threading.Thread(target=self._run,
300 args=(self,),
301 kwargs={'yet_another':self})
302 self.thread.start()
303
304 def _run(self, other_ref, yet_another):
305 if self.should_raise:
306 raise SystemExit
307
308 cyclic_object = RunSelfFunction(should_raise=False)
309 weak_cyclic_object = weakref.ref(cyclic_object)
310 cyclic_object.thread.join()
311 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000312 self.assertEquals(None, weak_cyclic_object(),
313 msg=('%d references still around' %
314 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000315
316 raising_cyclic_object = RunSelfFunction(should_raise=True)
317 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
318 raising_cyclic_object.thread.join()
319 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000320 self.assertEquals(None, weak_raising_cyclic_object(),
321 msg=('%d references still around' %
322 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000323
Christian Heimes1af737c2008-01-23 08:24:23 +0000324
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000325class ThreadingExceptionTests(unittest.TestCase):
326 # A RuntimeError should be raised if Thread.start() is called
327 # multiple times.
328 def test_start_thread_again(self):
329 thread = threading.Thread()
330 thread.start()
331 self.assertRaises(RuntimeError, thread.start)
332
333 def test_releasing_unacquired_rlock(self):
334 rlock = threading.RLock()
335 self.assertRaises(RuntimeError, rlock.release)
336
337 def test_waiting_on_unacquired_condition(self):
338 cond = threading.Condition()
339 self.assertRaises(RuntimeError, cond.wait)
340
341 def test_notify_on_unacquired_condition(self):
342 cond = threading.Condition()
343 self.assertRaises(RuntimeError, cond.notify)
344
345 def test_semaphore_with_negative_value(self):
346 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000347 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000348
349 def test_joining_current_thread(self):
350 currentThread = threading.currentThread()
351 self.assertRaises(RuntimeError, currentThread.join);
352
353 def test_joining_inactive_thread(self):
354 thread = threading.Thread()
355 self.assertRaises(RuntimeError, thread.join)
356
357 def test_daemonize_active_thread(self):
358 thread = threading.Thread()
359 thread.start()
360 self.assertRaises(RuntimeError, thread.setDaemon, True)
361
362
Tim Peters84d54892005-01-08 06:03:17 +0000363def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000364 test.support.run_unittest(ThreadTests,
Georg Brandl2067bfd2008-05-25 13:05:15 +0000365 ThreadingExceptionTests)
Tim Peters84d54892005-01-08 06:03:17 +0000366
367if __name__ == "__main__":
368 test_main()