blob: eabd7f4df4ef68c7ac64d74f0d6e6424d19d0c9d [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 Petersonfcf5d632008-10-16 23:24:44 +00004from 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' %
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)
Benjamin Petersond23f8222009-04-05 19:13:16 +000087 self.assertFalse(t.ident is None)
Georg Brandl0c77a822008-06-10 16:37:50 +000088 self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000089 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000090 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000091 self.assertEqual(numrunning.get(), 0)
92
Benjamin Petersond23f8222009-04-05 19:13:16 +000093 def test_ident_of_no_threading_threads(self):
94 # The ident still must work for the main thread and dummy threads.
95 self.assertFalse(threading.currentThread().ident is None)
96 def f():
97 ident.append(threading.currentThread().ident)
98 done.set()
99 done = threading.Event()
100 ident = []
101 _thread.start_new_thread(f, ())
102 done.wait()
103 self.assertFalse(ident[0] is None)
104
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105 # run with a small(ish) thread stack size (256kB)
106 def test_various_ops_small_stack(self):
107 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000108 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109 try:
110 threading.stack_size(262144)
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
118 # run with a large thread stack size (1MB)
119 def test_various_ops_large_stack(self):
120 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000121 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000122 try:
123 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000124 except _thread.error:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000125 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000126 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127 return
128 self.test_various_ops()
129 threading.stack_size(0)
130
Tim Peters711906e2005-01-08 07:30:42 +0000131 def test_foreign_thread(self):
132 # Check that a "foreign" thread can use the threading module.
133 def f(mutex):
134 # Acquiring an RLock forces an entry for the foreign
135 # thread to get made in the threading._active map.
136 r = threading.RLock()
137 r.acquire()
138 r.release()
139 mutex.release()
140
141 mutex = threading.Lock()
142 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000143 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000144 # Wait for the thread to finish.
145 mutex.acquire()
146 self.assert_(tid in threading._active)
147 self.assert_(isinstance(threading._active[tid],
148 threading._DummyThread))
149 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000150
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000151 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
152 # exposed at the Python level. This test relies on ctypes to get at it.
153 def test_PyThreadState_SetAsyncExc(self):
154 try:
155 import ctypes
156 except ImportError:
157 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000158 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000159 return # can't do anything
160
161 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
162
163 class AsyncExc(Exception):
164 pass
165
166 exception = ctypes.py_object(AsyncExc)
167
168 # `worker_started` is set by the thread when it's inside a try/except
169 # block waiting to catch the asynchronously set AsyncExc exception.
170 # `worker_saw_exception` is set by the thread upon catching that
171 # exception.
172 worker_started = threading.Event()
173 worker_saw_exception = threading.Event()
174
175 class Worker(threading.Thread):
176 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000177 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178 self.finished = False
179
180 try:
181 while True:
182 worker_started.set()
183 time.sleep(0.1)
184 except AsyncExc:
185 self.finished = True
186 worker_saw_exception.set()
187
188 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000189 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190 t.start()
191 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000192 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000193
194 # Try a thread id that doesn't make sense.
195 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000196 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197 result = set_async_exc(ctypes.c_long(-1), exception)
198 self.assertEqual(result, 0) # no thread states modified
199
200 # Now raise an exception in the worker thread.
201 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000202 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000203 ret = worker_started.wait()
204 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000205 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000206 print(" verifying worker hasn't exited")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000207 self.assert_(not t.finished)
208 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000209 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000210 result = set_async_exc(ctypes.c_long(t.id), exception)
211 self.assertEqual(result, 1) # one thread state modified
212 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000213 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000214 worker_saw_exception.wait(timeout=10)
215 self.assert_(t.finished)
216 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000217 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000218 if t.finished:
219 t.join()
220 # else the thread is still running, and we have no way to kill it
221
Christian Heimes7d2ff882007-11-30 14:35:04 +0000222 def test_finalize_runnning_thread(self):
223 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
224 # very late on python exit: on deallocation of a running thread for
225 # example.
226 try:
227 import ctypes
228 except ImportError:
229 if verbose:
230 print("test_finalize_with_runnning_thread can't import ctypes")
231 return # can't do anything
232
233 import subprocess
234 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000235 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000236
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000237 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000238 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000239 ready.acquire()
240
Christian Heimes7d2ff882007-11-30 14:35:04 +0000241 # Module globals are cleared before __del__ is run
242 # So we save the functions in class dict
243 class C:
244 ensure = ctypes.pythonapi.PyGILState_Ensure
245 release = ctypes.pythonapi.PyGILState_Release
246 def __del__(self):
247 state = self.ensure()
248 self.release(state)
249
250 def waitingThread():
251 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000252 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000253 time.sleep(100)
254
Georg Brandl2067bfd2008-05-25 13:05:15 +0000255 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000256 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000257 sys.exit(42)
258 """])
259 self.assertEqual(rc, 42)
260
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000261 def test_finalize_with_trace(self):
262 # Issue1733757
263 # Avoid a deadlock when sys.settrace steps into threading._shutdown
264 import subprocess
265 rc = subprocess.call([sys.executable, "-c", """if 1:
266 import sys, threading
267
268 # A deadlock-killer, to prevent the
269 # testsuite to hang forever
270 def killer():
271 import os, time
272 time.sleep(2)
273 print('program blocked; aborting')
274 os._exit(2)
275 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000276 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000277 t.start()
278
279 # This is the trace function
280 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000281 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000282 return func
283
284 sys.settrace(func)
285 """])
286 self.failIf(rc == 2, "interpreted was blocked")
287 self.failUnless(rc == 0, "Unexpected error")
288
289
Christian Heimes1af737c2008-01-23 08:24:23 +0000290 def test_enumerate_after_join(self):
291 # Try hard to trigger #1703448: a thread is still returned in
292 # threading.enumerate() after it has been join()ed.
293 enum = threading.enumerate
294 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000295 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000296 for i in range(1, 100):
297 # Try a couple times at each thread-switching interval
298 # to get more interleavings.
299 sys.setcheckinterval(i // 5)
Christian Heimes1af737c2008-01-23 08:24:23 +0000300 t = threading.Thread(target=lambda: None)
301 t.start()
302 t.join()
303 l = enum()
304 self.assertFalse(t in l,
305 "#1703448 triggered after %d trials: %s" % (i, l))
306 finally:
307 sys.setcheckinterval(old_interval)
308
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000309 def test_no_refcycle_through_target(self):
310 class RunSelfFunction(object):
311 def __init__(self, should_raise):
312 # The links in this refcycle from Thread back to self
313 # should be cleaned up when the thread completes.
314 self.should_raise = should_raise
315 self.thread = threading.Thread(target=self._run,
316 args=(self,),
317 kwargs={'yet_another':self})
318 self.thread.start()
319
320 def _run(self, other_ref, yet_another):
321 if self.should_raise:
322 raise SystemExit
323
324 cyclic_object = RunSelfFunction(should_raise=False)
325 weak_cyclic_object = weakref.ref(cyclic_object)
326 cyclic_object.thread.join()
327 del cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000328 self.assertEquals(None, weak_cyclic_object(),
329 msg=('%d references still around' %
330 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000331
332 raising_cyclic_object = RunSelfFunction(should_raise=True)
333 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
334 raising_cyclic_object.thread.join()
335 del raising_cyclic_object
Christian Heimesbbe741d2008-03-28 10:53:29 +0000336 self.assertEquals(None, weak_raising_cyclic_object(),
337 msg=('%d references still around' %
338 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000339
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000340 def test_old_threading_api(self):
341 # Just a quick sanity check to make sure the old method names are
342 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000343 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000344 t.isDaemon()
345 t.setDaemon(True)
346 t.getName()
347 t.setName("name")
348 t.isAlive()
349 e = threading.Event()
350 e.isSet()
351 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000352
Christian Heimes1af737c2008-01-23 08:24:23 +0000353
Jesse Nollera8513972008-07-17 16:49:17 +0000354class ThreadJoinOnShutdown(unittest.TestCase):
355
356 def _run_and_join(self, script):
357 script = """if 1:
358 import sys, os, time, threading
359
360 # a thread, which waits for the main program to terminate
361 def joiningfunc(mainthread):
362 mainthread.join()
363 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000364 # stdout is fully buffered because not a tty, we have to flush
365 # before exit.
366 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000367 \n""" + script
368
369 import subprocess
370 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
371 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000372 data = p.stdout.read().decode().replace('\r', '')
373 self.assertEqual(data, "end of main\nend of thread\n")
Jesse Nollera8513972008-07-17 16:49:17 +0000374 self.failIf(rc == 2, "interpreter was blocked")
375 self.failUnless(rc == 0, "Unexpected error")
376
377 def test_1_join_on_shutdown(self):
378 # The usual case: on exit, wait for a non-daemon thread
379 script = """if 1:
380 import os
381 t = threading.Thread(target=joiningfunc,
382 args=(threading.current_thread(),))
383 t.start()
384 time.sleep(0.1)
385 print('end of main')
386 """
387 self._run_and_join(script)
388
389
390 def test_2_join_in_forked_process(self):
391 # Like the test above, but from a forked interpreter
392 import os
393 if not hasattr(os, 'fork'):
394 return
395 script = """if 1:
396 childpid = os.fork()
397 if childpid != 0:
398 os.waitpid(childpid, 0)
399 sys.exit(0)
400
401 t = threading.Thread(target=joiningfunc,
402 args=(threading.current_thread(),))
403 t.start()
404 print('end of main')
405 """
406 self._run_and_join(script)
407
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000408 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000409 # Like the test above, but fork() was called from a worker thread
410 # In the forked process, the main Thread object must be marked as stopped.
411 import os
412 if not hasattr(os, 'fork'):
413 return
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000414 # Skip platforms with known problems forking from a worker thread.
415 # See http://bugs.python.org/issue3863.
416 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
417 print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread'
418 ' due to known OS bugs on'), sys.platform
419 return
Jesse Nollera8513972008-07-17 16:49:17 +0000420 script = """if 1:
421 main_thread = threading.current_thread()
422 def worker():
423 childpid = os.fork()
424 if childpid != 0:
425 os.waitpid(childpid, 0)
426 sys.exit(0)
427
428 t = threading.Thread(target=joiningfunc,
429 args=(main_thread,))
430 print('end of main')
431 t.start()
432 t.join() # Should not block: main_thread is already stopped
433
434 w = threading.Thread(target=worker)
435 w.start()
436 """
437 self._run_and_join(script)
438
439
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000440class ThreadingExceptionTests(unittest.TestCase):
441 # A RuntimeError should be raised if Thread.start() is called
442 # multiple times.
443 def test_start_thread_again(self):
444 thread = threading.Thread()
445 thread.start()
446 self.assertRaises(RuntimeError, thread.start)
447
448 def test_releasing_unacquired_rlock(self):
449 rlock = threading.RLock()
450 self.assertRaises(RuntimeError, rlock.release)
451
452 def test_waiting_on_unacquired_condition(self):
453 cond = threading.Condition()
454 self.assertRaises(RuntimeError, cond.wait)
455
456 def test_notify_on_unacquired_condition(self):
457 cond = threading.Condition()
458 self.assertRaises(RuntimeError, cond.notify)
459
460 def test_semaphore_with_negative_value(self):
461 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000462 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000463
464 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000465 current_thread = threading.current_thread()
466 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000467
468 def test_joining_inactive_thread(self):
469 thread = threading.Thread()
470 self.assertRaises(RuntimeError, thread.join)
471
472 def test_daemonize_active_thread(self):
473 thread = threading.Thread()
474 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000475 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000476
477
Tim Peters84d54892005-01-08 06:03:17 +0000478def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000479 test.support.run_unittest(ThreadTests,
Jesse Nollera8513972008-07-17 16:49:17 +0000480 ThreadJoinOnShutdown,
481 ThreadingExceptionTests,
482 )
Tim Peters84d54892005-01-08 06:03:17 +0000483
484if __name__ == "__main__":
485 test_main()