blob: f26e7bb4e72f011a1ebadfaf81161684badbe280 [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
Benjamin Petersonf0923f52008-08-18 22:10:13 +00004from test.support import verbose, catch_warning
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' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000037 (self.name, 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:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000048 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000049
Christian Heimes4fbc72b2008-03-22 00:47:35 +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 Petersonfdbea962008-08-18 17:33:47 +000055 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000056
Skip Montanaro4533f602001-08-20 20:28:48 +000057
Tim Peters84d54892005-01-08 06:03:17 +000058class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000059
Tim Peters84d54892005-01-08 06:03:17 +000060 # Create a bunch of threads, let each do some work, wait until all are
61 # done.
62 def test_various_ops(self):
63 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
64 # times about 1 second per clump).
65 NUMTASKS = 10
66
67 # no more than 3 of the 10 can run at once
68 sema = threading.BoundedSemaphore(value=3)
69 mutex = threading.RLock()
70 numrunning = Counter()
71
72 threads = []
73
74 for i in range(NUMTASKS):
75 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
76 threads.append(t)
Benjamin Peterson773c17b2008-08-18 16:45:31 +000077 self.failUnlessEqual(t.ident, None)
Georg Brandl0c77a822008-06-10 16:37:50 +000078 self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000079 t.start()
80
81 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000082 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000083 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000084 t.join(NUMTASKS)
Benjamin Peterson672b8032008-06-11 19:14:14 +000085 self.assert_(not t.is_alive())
Benjamin Peterson773c17b2008-08-18 16:45:31 +000086 self.failIfEqual(t.ident, 0)
Georg Brandl0c77a822008-06-10 16:37:50 +000087 self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000088 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000089 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000090 self.assertEqual(numrunning.get(), 0)
91
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092 # run with a small(ish) thread stack size (256kB)
93 def test_various_ops_small_stack(self):
94 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000095 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000096 try:
97 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +000098 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000100 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000101 return
102 self.test_various_ops()
103 threading.stack_size(0)
104
105 # run with a large thread stack size (1MB)
106 def test_various_ops_large_stack(self):
107 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000108 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109 try:
110 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000111 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000113 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114 return
115 self.test_various_ops()
116 threading.stack_size(0)
117
Tim Peters711906e2005-01-08 07:30:42 +0000118 def test_foreign_thread(self):
119 # Check that a "foreign" thread can use the threading module.
120 def f(mutex):
121 # Acquiring an RLock forces an entry for the foreign
122 # thread to get made in the threading._active map.
123 r = threading.RLock()
124 r.acquire()
125 r.release()
126 mutex.release()
127
128 mutex = threading.Lock()
129 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000130 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000131 # Wait for the thread to finish.
132 mutex.acquire()
133 self.assert_(tid in threading._active)
134 self.assert_(isinstance(threading._active[tid],
135 threading._DummyThread))
136 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000137
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000138 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
139 # exposed at the Python level. This test relies on ctypes to get at it.
140 def test_PyThreadState_SetAsyncExc(self):
141 try:
142 import ctypes
143 except ImportError:
144 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000145 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000146 return # can't do anything
147
148 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
149
150 class AsyncExc(Exception):
151 pass
152
153 exception = ctypes.py_object(AsyncExc)
154
155 # `worker_started` is set by the thread when it's inside a try/except
156 # block waiting to catch the asynchronously set AsyncExc exception.
157 # `worker_saw_exception` is set by the thread upon catching that
158 # exception.
159 worker_started = threading.Event()
160 worker_saw_exception = threading.Event()
161
162 class Worker(threading.Thread):
163 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000164 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000165 self.finished = False
166
167 try:
168 while True:
169 worker_started.set()
170 time.sleep(0.1)
171 except AsyncExc:
172 self.finished = True
173 worker_saw_exception.set()
174
175 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000176 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000177 t.start()
178 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000179 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000180
181 # Try a thread id that doesn't make sense.
182 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000183 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000184 result = set_async_exc(ctypes.c_long(-1), exception)
185 self.assertEqual(result, 0) # no thread states modified
186
187 # Now raise an exception in the worker thread.
188 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000189 print(" waiting for worker thread to get started")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190 worker_started.wait()
191 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000192 print(" verifying worker hasn't exited")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000193 self.assert_(not t.finished)
194 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000195 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000196 result = set_async_exc(ctypes.c_long(t.id), exception)
197 self.assertEqual(result, 1) # one thread state modified
198 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000199 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000200 worker_saw_exception.wait(timeout=10)
201 self.assert_(t.finished)
202 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000203 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000204 if t.finished:
205 t.join()
206 # else the thread is still running, and we have no way to kill it
207
Christian Heimes7d2ff882007-11-30 14:35:04 +0000208 def test_finalize_runnning_thread(self):
209 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
210 # very late on python exit: on deallocation of a running thread for
211 # example.
212 try:
213 import ctypes
214 except ImportError:
215 if verbose:
216 print("test_finalize_with_runnning_thread can't import ctypes")
217 return # can't do anything
218
219 import subprocess
220 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000221 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000222
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000223 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000224 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000225 ready.acquire()
226
Christian Heimes7d2ff882007-11-30 14:35:04 +0000227 # Module globals are cleared before __del__ is run
228 # So we save the functions in class dict
229 class C:
230 ensure = ctypes.pythonapi.PyGILState_Ensure
231 release = ctypes.pythonapi.PyGILState_Release
232 def __del__(self):
233 state = self.ensure()
234 self.release(state)
235
236 def waitingThread():
237 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000238 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000239 time.sleep(100)
240
Georg Brandl2067bfd2008-05-25 13:05:15 +0000241 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000242 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000243 sys.exit(42)
244 """])
245 self.assertEqual(rc, 42)
246
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000247 def test_finalize_with_trace(self):
248 # Issue1733757
249 # Avoid a deadlock when sys.settrace steps into threading._shutdown
250 import subprocess
251 rc = subprocess.call([sys.executable, "-c", """if 1:
252 import sys, threading
253
254 # A deadlock-killer, to prevent the
255 # testsuite to hang forever
256 def killer():
257 import os, time
258 time.sleep(2)
259 print('program blocked; aborting')
260 os._exit(2)
261 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000262 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000263 t.start()
264
265 # This is the trace function
266 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000267 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000268 return func
269
270 sys.settrace(func)
271 """])
272 self.failIf(rc == 2, "interpreted was blocked")
273 self.failUnless(rc == 0, "Unexpected error")
274
275
Christian Heimes1af737c2008-01-23 08:24:23 +0000276 def test_enumerate_after_join(self):
277 # Try hard to trigger #1703448: a thread is still returned in
278 # threading.enumerate() after it has been join()ed.
279 enum = threading.enumerate
280 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000281 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000282 for i in range(1, 100):
283 # Try a couple times at each thread-switching interval
284 # to get more interleavings.
285 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000286 t = threading.Thread(target=lambda: None)
287 t.start()
288 t.join()
289 l = enum()
290 self.assertFalse(t in l,
291 "#1703448 triggered after %d trials: %s" % (i, l))
292 finally:
293 sys.setcheckinterval(old_interval)
294
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000295 def test_no_refcycle_through_target(self):
296 class RunSelfFunction(object):
297 def __init__(self, should_raise):
298 # The links in this refcycle from Thread back to self
299 # should be cleaned up when the thread completes.
300 self.should_raise = should_raise
301 self.thread = threading.Thread(target=self._run,
302 args=(self,),
303 kwargs={'yet_another':self})
304 self.thread.start()
305
306 def _run(self, other_ref, yet_another):
307 if self.should_raise:
308 raise SystemExit
309
310 cyclic_object = RunSelfFunction(should_raise=False)
311 weak_cyclic_object = weakref.ref(cyclic_object)
312 cyclic_object.thread.join()
313 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000314 self.assertEquals(None, weak_cyclic_object(),
315 msg=('%d references still around' %
316 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000317
318 raising_cyclic_object = RunSelfFunction(should_raise=True)
319 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
320 raising_cyclic_object.thread.join()
321 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000322 self.assertEquals(None, weak_raising_cyclic_object(),
323 msg=('%d references still around' %
324 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000325
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000326 def test_old_threading_api(self):
327 # Just a quick sanity check to make sure the old method names are
328 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000329 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000330 t.isDaemon()
331 t.setDaemon(True)
332 t.getName()
333 t.setName("name")
334 t.isAlive()
335 e = threading.Event()
336 e.isSet()
337 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000338
Christian Heimes1af737c2008-01-23 08:24:23 +0000339
Jesse Nollera8513972008-07-17 16:49:17 +0000340class ThreadJoinOnShutdown(unittest.TestCase):
341
342 def _run_and_join(self, script):
343 script = """if 1:
344 import sys, os, time, threading
345
346 # a thread, which waits for the main program to terminate
347 def joiningfunc(mainthread):
348 mainthread.join()
349 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000350 # stdout is fully buffered because not a tty, we have to flush
351 # before exit.
352 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000353 \n""" + script
354
355 import subprocess
356 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
357 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000358 data = p.stdout.read().decode().replace('\r', '')
359 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000360 self.failIf(rc == 2, "interpreter was blocked")
361 self.failUnless(rc == 0, "Unexpected error")
362
363 def test_1_join_on_shutdown(self):
364 # The usual case: on exit, wait for a non-daemon thread
365 script = """if 1:
366 import os
367 t = threading.Thread(target=joiningfunc,
368 args=(threading.current_thread(),))
369 t.start()
370 time.sleep(0.1)
371 print('end of main')
372 """
373 self._run_and_join(script)
374
375
376 def test_2_join_in_forked_process(self):
377 # Like the test above, but from a forked interpreter
378 import os
379 if not hasattr(os, 'fork'):
380 return
381 script = """if 1:
382 childpid = os.fork()
383 if childpid != 0:
384 os.waitpid(childpid, 0)
385 sys.exit(0)
386
387 t = threading.Thread(target=joiningfunc,
388 args=(threading.current_thread(),))
389 t.start()
390 print('end of main')
391 """
392 self._run_and_join(script)
393
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000394 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000395 # Like the test above, but fork() was called from a worker thread
396 # In the forked process, the main Thread object must be marked as stopped.
397 import os
398 if not hasattr(os, 'fork'):
399 return
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000400 # Skip platforms with known problems forking from a worker thread.
401 # See http://bugs.python.org/issue3863.
402 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
403 print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread'
404 ' due to known OS bugs on'), sys.platform
405 return
Jesse Nollera8513972008-07-17 16:49:17 +0000406 script = """if 1:
407 main_thread = threading.current_thread()
408 def worker():
409 childpid = os.fork()
410 if childpid != 0:
411 os.waitpid(childpid, 0)
412 sys.exit(0)
413
414 t = threading.Thread(target=joiningfunc,
415 args=(main_thread,))
416 print('end of main')
417 t.start()
418 t.join() # Should not block: main_thread is already stopped
419
420 w = threading.Thread(target=worker)
421 w.start()
422 """
423 self._run_and_join(script)
424
425
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000426class ThreadingExceptionTests(unittest.TestCase):
427 # A RuntimeError should be raised if Thread.start() is called
428 # multiple times.
429 def test_start_thread_again(self):
430 thread = threading.Thread()
431 thread.start()
432 self.assertRaises(RuntimeError, thread.start)
433
434 def test_releasing_unacquired_rlock(self):
435 rlock = threading.RLock()
436 self.assertRaises(RuntimeError, rlock.release)
437
438 def test_waiting_on_unacquired_condition(self):
439 cond = threading.Condition()
440 self.assertRaises(RuntimeError, cond.wait)
441
442 def test_notify_on_unacquired_condition(self):
443 cond = threading.Condition()
444 self.assertRaises(RuntimeError, cond.notify)
445
446 def test_semaphore_with_negative_value(self):
447 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000448 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000449
450 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000451 current_thread = threading.current_thread()
452 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000453
454 def test_joining_inactive_thread(self):
455 thread = threading.Thread()
456 self.assertRaises(RuntimeError, thread.join)
457
458 def test_daemonize_active_thread(self):
459 thread = threading.Thread()
460 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000461 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000462
463
Tim Peters84d54892005-01-08 06:03:17 +0000464def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000465 test.support.run_unittest(ThreadTests,
Jesse Nollera8513972008-07-17 16:49:17 +0000466 ThreadJoinOnShutdown,
467 ThreadingExceptionTests,
468 )
Tim Peters84d54892005-01-08 06:03:17 +0000469
470if __name__ == "__main__":
471 test_main()