blob: 3c09b0bd272701a555d7a2f4d48758496e8aa7a1 [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
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006import sys
Skip Montanaro4533f602001-08-20 20:28:48 +00007import threading
Georg Brandl2067bfd2008-05-25 13:05:15 +00008import _thread
Skip Montanaro4533f602001-08-20 20:28:48 +00009import time
Tim Peters84d54892005-01-08 06:03:17 +000010import unittest
Christian Heimesd3eb5a152008-02-24 00:38:49 +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):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000033 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000034 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000035 print('task %s will run for %.1f usec' %
36 (self.getName(), delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000037
Christian Heimes4fbc72b2008-03-22 00:47:35 +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
Christian Heimes4fbc72b2008-03-22 00:47:35 +000045 time.sleep(delay)
46 if verbose:
47 print('task', self.getName(), 'done')
48 with self.mutex:
49 self.nrunning.dec()
50 self.testcase.assert_(self.nrunning.get() >= 0)
51 if verbose:
52 print('%s is finished. %d tasks are running' %
Jeffrey Yasskinca674122008-03-29 05:06:52 +000053 (self.getName(), self.nrunning.get()))
Skip Montanaro4533f602001-08-20 20:28:48 +000054
Tim Peters84d54892005-01-08 06:03:17 +000055class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000056
Tim Peters84d54892005-01-08 06:03:17 +000057 # Create a bunch of threads, let each do some work, wait until all are
58 # done.
59 def test_various_ops(self):
60 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
61 # times about 1 second per clump).
62 NUMTASKS = 10
63
64 # no more than 3 of the 10 can run at once
65 sema = threading.BoundedSemaphore(value=3)
66 mutex = threading.RLock()
67 numrunning = Counter()
68
69 threads = []
70
71 for i in range(NUMTASKS):
72 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
73 threads.append(t)
74 t.start()
75
76 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000077 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000078 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000079 t.join(NUMTASKS)
80 self.assert_(not t.isAlive())
Tim Peters84d54892005-01-08 06:03:17 +000081 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000082 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000083 self.assertEqual(numrunning.get(), 0)
84
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085 # run with a small(ish) thread stack size (256kB)
86 def test_various_ops_small_stack(self):
87 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000088 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089 try:
90 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +000091 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000093 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094 return
95 self.test_various_ops()
96 threading.stack_size(0)
97
98 # run with a large thread stack size (1MB)
99 def test_various_ops_large_stack(self):
100 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000101 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000102 try:
103 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000104 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000106 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107 return
108 self.test_various_ops()
109 threading.stack_size(0)
110
Tim Peters711906e2005-01-08 07:30:42 +0000111 def test_foreign_thread(self):
112 # Check that a "foreign" thread can use the threading module.
113 def f(mutex):
114 # Acquiring an RLock forces an entry for the foreign
115 # thread to get made in the threading._active map.
116 r = threading.RLock()
117 r.acquire()
118 r.release()
119 mutex.release()
120
121 mutex = threading.Lock()
122 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000123 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000124 # Wait for the thread to finish.
125 mutex.acquire()
126 self.assert_(tid in threading._active)
127 self.assert_(isinstance(threading._active[tid],
128 threading._DummyThread))
129 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000130
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000131 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
132 # exposed at the Python level. This test relies on ctypes to get at it.
133 def test_PyThreadState_SetAsyncExc(self):
134 try:
135 import ctypes
136 except ImportError:
137 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000138 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000139 return # can't do anything
140
141 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
142
143 class AsyncExc(Exception):
144 pass
145
146 exception = ctypes.py_object(AsyncExc)
147
148 # `worker_started` is set by the thread when it's inside a try/except
149 # block waiting to catch the asynchronously set AsyncExc exception.
150 # `worker_saw_exception` is set by the thread upon catching that
151 # exception.
152 worker_started = threading.Event()
153 worker_saw_exception = threading.Event()
154
155 class Worker(threading.Thread):
156 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000157 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000158 self.finished = False
159
160 try:
161 while True:
162 worker_started.set()
163 time.sleep(0.1)
164 except AsyncExc:
165 self.finished = True
166 worker_saw_exception.set()
167
168 t = Worker()
169 t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
170 t.start()
171 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000172 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000173
174 # Try a thread id that doesn't make sense.
175 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000176 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000177 result = set_async_exc(ctypes.c_long(-1), exception)
178 self.assertEqual(result, 0) # no thread states modified
179
180 # Now raise an exception in the worker thread.
181 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000182 print(" waiting for worker thread to get started")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000183 worker_started.wait()
184 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000185 print(" verifying worker hasn't exited")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000186 self.assert_(not t.finished)
187 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000188 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000189 result = set_async_exc(ctypes.c_long(t.id), exception)
190 self.assertEqual(result, 1) # one thread state modified
191 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000192 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000193 worker_saw_exception.wait(timeout=10)
194 self.assert_(t.finished)
195 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000196 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197 if t.finished:
198 t.join()
199 # else the thread is still running, and we have no way to kill it
200
Christian Heimes7d2ff882007-11-30 14:35:04 +0000201 def test_finalize_runnning_thread(self):
202 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
203 # very late on python exit: on deallocation of a running thread for
204 # example.
205 try:
206 import ctypes
207 except ImportError:
208 if verbose:
209 print("test_finalize_with_runnning_thread can't import ctypes")
210 return # can't do anything
211
212 import subprocess
213 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000214 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000215
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000216 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000217 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000218 ready.acquire()
219
Christian Heimes7d2ff882007-11-30 14:35:04 +0000220 # Module globals are cleared before __del__ is run
221 # So we save the functions in class dict
222 class C:
223 ensure = ctypes.pythonapi.PyGILState_Ensure
224 release = ctypes.pythonapi.PyGILState_Release
225 def __del__(self):
226 state = self.ensure()
227 self.release(state)
228
229 def waitingThread():
230 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000231 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000232 time.sleep(100)
233
Georg Brandl2067bfd2008-05-25 13:05:15 +0000234 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000235 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000236 sys.exit(42)
237 """])
238 self.assertEqual(rc, 42)
239
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000240 def test_finalize_with_trace(self):
241 # Issue1733757
242 # Avoid a deadlock when sys.settrace steps into threading._shutdown
243 import subprocess
244 rc = subprocess.call([sys.executable, "-c", """if 1:
245 import sys, threading
246
247 # A deadlock-killer, to prevent the
248 # testsuite to hang forever
249 def killer():
250 import os, time
251 time.sleep(2)
252 print('program blocked; aborting')
253 os._exit(2)
254 t = threading.Thread(target=killer)
255 t.setDaemon(True)
256 t.start()
257
258 # This is the trace function
259 def func(frame, event, arg):
260 threading.currentThread()
261 return func
262
263 sys.settrace(func)
264 """])
265 self.failIf(rc == 2, "interpreted was blocked")
266 self.failUnless(rc == 0, "Unexpected error")
267
268
Christian Heimes1af737c2008-01-23 08:24:23 +0000269 def test_enumerate_after_join(self):
270 # Try hard to trigger #1703448: a thread is still returned in
271 # threading.enumerate() after it has been join()ed.
272 enum = threading.enumerate
273 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000274 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000275 for i in range(1, 100):
276 # Try a couple times at each thread-switching interval
277 # to get more interleavings.
278 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000279 t = threading.Thread(target=lambda: None)
280 t.start()
281 t.join()
282 l = enum()
283 self.assertFalse(t in l,
284 "#1703448 triggered after %d trials: %s" % (i, l))
285 finally:
286 sys.setcheckinterval(old_interval)
287
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000288 def test_no_refcycle_through_target(self):
289 class RunSelfFunction(object):
290 def __init__(self, should_raise):
291 # The links in this refcycle from Thread back to self
292 # should be cleaned up when the thread completes.
293 self.should_raise = should_raise
294 self.thread = threading.Thread(target=self._run,
295 args=(self,),
296 kwargs={'yet_another':self})
297 self.thread.start()
298
299 def _run(self, other_ref, yet_another):
300 if self.should_raise:
301 raise SystemExit
302
303 cyclic_object = RunSelfFunction(should_raise=False)
304 weak_cyclic_object = weakref.ref(cyclic_object)
305 cyclic_object.thread.join()
306 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000307 self.assertEquals(None, weak_cyclic_object(),
308 msg=('%d references still around' %
309 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000310
311 raising_cyclic_object = RunSelfFunction(should_raise=True)
312 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
313 raising_cyclic_object.thread.join()
314 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000315 self.assertEquals(None, weak_raising_cyclic_object(),
316 msg=('%d references still around' %
317 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000318
Christian Heimes1af737c2008-01-23 08:24:23 +0000319
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000320class ThreadingExceptionTests(unittest.TestCase):
321 # A RuntimeError should be raised if Thread.start() is called
322 # multiple times.
323 def test_start_thread_again(self):
324 thread = threading.Thread()
325 thread.start()
326 self.assertRaises(RuntimeError, thread.start)
327
328 def test_releasing_unacquired_rlock(self):
329 rlock = threading.RLock()
330 self.assertRaises(RuntimeError, rlock.release)
331
332 def test_waiting_on_unacquired_condition(self):
333 cond = threading.Condition()
334 self.assertRaises(RuntimeError, cond.wait)
335
336 def test_notify_on_unacquired_condition(self):
337 cond = threading.Condition()
338 self.assertRaises(RuntimeError, cond.notify)
339
340 def test_semaphore_with_negative_value(self):
341 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000342 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000343
344 def test_joining_current_thread(self):
345 currentThread = threading.currentThread()
346 self.assertRaises(RuntimeError, currentThread.join);
347
348 def test_joining_inactive_thread(self):
349 thread = threading.Thread()
350 self.assertRaises(RuntimeError, thread.join)
351
352 def test_daemonize_active_thread(self):
353 thread = threading.Thread()
354 thread.start()
355 self.assertRaises(RuntimeError, thread.setDaemon, True)
356
357
Tim Peters84d54892005-01-08 06:03:17 +0000358def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000359 test.support.run_unittest(ThreadTests,
Georg Brandl2067bfd2008-05-25 13:05:15 +0000360 ThreadingExceptionTests)
Tim Peters84d54892005-01-08 06:03:17 +0000361
362if __name__ == "__main__":
363 test_main()