blob: 12edf4290139fca9177f8a472887ff3a6472863c [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
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00004from test.support import verbose, strip_python_stderr
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
Victor Stinner45df8202010-04-28 22:31:17 +00008_thread = test.support.import_module('_thread')
9threading = test.support.import_module('threading')
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
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +000013import os
Skip Montanaro4533f602001-08-20 20:28:48 +000014
Antoine Pitrou557934f2009-11-06 22:41:14 +000015from test import lock_tests
16
Tim Peters84d54892005-01-08 06:03:17 +000017# A trivial mutable counter.
18class Counter(object):
19 def __init__(self):
20 self.value = 0
21 def inc(self):
22 self.value += 1
23 def dec(self):
24 self.value -= 1
25 def get(self):
26 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000027
28class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000029 def __init__(self, name, testcase, sema, mutex, nrunning):
30 threading.Thread.__init__(self, name=name)
31 self.testcase = testcase
32 self.sema = sema
33 self.mutex = mutex
34 self.nrunning = nrunning
35
Skip Montanaro4533f602001-08-20 20:28:48 +000036 def run(self):
Christian Heimes4fbc72b2008-03-22 00:47:35 +000037 delay = random.random() / 10000.0
Skip Montanaro4533f602001-08-20 20:28:48 +000038 if verbose:
Jeffrey Yasskinca674122008-03-29 05:06:52 +000039 print('task %s will run for %.1f usec' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000040 (self.name, delay * 1e6))
Tim Peters84d54892005-01-08 06:03:17 +000041
Christian Heimes4fbc72b2008-03-22 00:47:35 +000042 with self.sema:
43 with self.mutex:
44 self.nrunning.inc()
45 if verbose:
46 print(self.nrunning.get(), 'tasks are running')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000047 self.testcase.assertTrue(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000048
Christian Heimes4fbc72b2008-03-22 00:47:35 +000049 time.sleep(delay)
50 if verbose:
Benjamin Petersonfdbea962008-08-18 17:33:47 +000051 print('task', self.name, 'done')
Benjamin Peterson672b8032008-06-11 19:14:14 +000052
Christian Heimes4fbc72b2008-03-22 00:47:35 +000053 with self.mutex:
54 self.nrunning.dec()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000055 self.testcase.assertTrue(self.nrunning.get() >= 0)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000056 if verbose:
57 print('%s is finished. %d tasks are running' %
Benjamin Petersonfdbea962008-08-18 17:33:47 +000058 (self.name, self.nrunning.get()))
Benjamin Peterson672b8032008-06-11 19:14:14 +000059
Skip Montanaro4533f602001-08-20 20:28:48 +000060
Antoine Pitroub0e9bd42009-10-27 20:05:26 +000061class BaseTestCase(unittest.TestCase):
62 def setUp(self):
63 self._threads = test.support.threading_setup()
64
65 def tearDown(self):
66 test.support.threading_cleanup(*self._threads)
67 test.support.reap_children()
68
69
70class ThreadTests(BaseTestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000071
Tim Peters84d54892005-01-08 06:03:17 +000072 # Create a bunch of threads, let each do some work, wait until all are
73 # done.
74 def test_various_ops(self):
75 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
76 # times about 1 second per clump).
77 NUMTASKS = 10
78
79 # no more than 3 of the 10 can run at once
80 sema = threading.BoundedSemaphore(value=3)
81 mutex = threading.RLock()
82 numrunning = Counter()
83
84 threads = []
85
86 for i in range(NUMTASKS):
87 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
88 threads.append(t)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000089 self.assertEqual(t.ident, None)
90 self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +000091 t.start()
92
93 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000094 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000095 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000096 t.join(NUMTASKS)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000097 self.assertTrue(not t.is_alive())
98 self.assertNotEqual(t.ident, 0)
Benjamin Petersond23f8222009-04-05 19:13:16 +000099 self.assertFalse(t.ident is None)
Brett Cannon3f5f2262010-07-23 15:50:52 +0000100 self.assertTrue(re.match('<TestThread\(.*, stopped -?\d+\)>',
101 repr(t)))
Tim Peters84d54892005-01-08 06:03:17 +0000102 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000103 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +0000104 self.assertEqual(numrunning.get(), 0)
105
Benjamin Petersond23f8222009-04-05 19:13:16 +0000106 def test_ident_of_no_threading_threads(self):
107 # The ident still must work for the main thread and dummy threads.
108 self.assertFalse(threading.currentThread().ident is None)
109 def f():
110 ident.append(threading.currentThread().ident)
111 done.set()
112 done = threading.Event()
113 ident = []
114 _thread.start_new_thread(f, ())
115 done.wait()
116 self.assertFalse(ident[0] is None)
Antoine Pitrouca13a0d2009-11-08 00:30:04 +0000117 # Kill the "immortal" _DummyThread
118 del threading._active[ident[0]]
Benjamin Petersond23f8222009-04-05 19:13:16 +0000119
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120 # run with a small(ish) thread stack size (256kB)
121 def test_various_ops_small_stack(self):
122 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000123 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000124 try:
125 threading.stack_size(262144)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000126 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000127 raise unittest.SkipTest(
128 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000129 self.test_various_ops()
130 threading.stack_size(0)
131
132 # run with a large thread stack size (1MB)
133 def test_various_ops_large_stack(self):
134 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000135 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000136 try:
137 threading.stack_size(0x100000)
Georg Brandl2067bfd2008-05-25 13:05:15 +0000138 except _thread.error:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000139 raise unittest.SkipTest(
140 'platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141 self.test_various_ops()
142 threading.stack_size(0)
143
Tim Peters711906e2005-01-08 07:30:42 +0000144 def test_foreign_thread(self):
145 # Check that a "foreign" thread can use the threading module.
146 def f(mutex):
Antoine Pitroub0872682009-11-09 16:08:16 +0000147 # Calling current_thread() forces an entry for the foreign
Tim Peters711906e2005-01-08 07:30:42 +0000148 # thread to get made in the threading._active map.
Antoine Pitroub0872682009-11-09 16:08:16 +0000149 threading.current_thread()
Tim Peters711906e2005-01-08 07:30:42 +0000150 mutex.release()
151
152 mutex = threading.Lock()
153 mutex.acquire()
Georg Brandl2067bfd2008-05-25 13:05:15 +0000154 tid = _thread.start_new_thread(f, (mutex,))
Tim Peters711906e2005-01-08 07:30:42 +0000155 # Wait for the thread to finish.
156 mutex.acquire()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000157 self.assertIn(tid, threading._active)
Ezio Melottie9615932010-01-24 19:26:24 +0000158 self.assertIsInstance(threading._active[tid], threading._DummyThread)
Tim Peters711906e2005-01-08 07:30:42 +0000159 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000160
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000161 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
162 # exposed at the Python level. This test relies on ctypes to get at it.
163 def test_PyThreadState_SetAsyncExc(self):
164 try:
165 import ctypes
166 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000167 raise unittest.SkipTest("cannot import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000168
169 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
170
171 class AsyncExc(Exception):
172 pass
173
174 exception = ctypes.py_object(AsyncExc)
175
Antoine Pitroube4d8092009-10-18 18:27:17 +0000176 # First check it works when setting the exception from the same thread.
177 tid = _thread.get_ident()
178
179 try:
180 result = set_async_exc(ctypes.c_long(tid), exception)
181 # The exception is async, so we might have to keep the VM busy until
182 # it notices.
183 while True:
184 pass
185 except AsyncExc:
186 pass
187 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000188 # This code is unreachable but it reflects the intent. If we wanted
189 # to be smarter the above loop wouldn't be infinite.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000190 self.fail("AsyncExc not raised")
191 try:
192 self.assertEqual(result, 1) # one thread state modified
193 except UnboundLocalError:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000194 # The exception was raised too quickly for us to get the result.
Antoine Pitroube4d8092009-10-18 18:27:17 +0000195 pass
196
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197 # `worker_started` is set by the thread when it's inside a try/except
198 # block waiting to catch the asynchronously set AsyncExc exception.
199 # `worker_saw_exception` is set by the thread upon catching that
200 # exception.
201 worker_started = threading.Event()
202 worker_saw_exception = threading.Event()
203
204 class Worker(threading.Thread):
205 def run(self):
Georg Brandl2067bfd2008-05-25 13:05:15 +0000206 self.id = _thread.get_ident()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000207 self.finished = False
208
209 try:
210 while True:
211 worker_started.set()
212 time.sleep(0.1)
213 except AsyncExc:
214 self.finished = True
215 worker_saw_exception.set()
216
217 t = Worker()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000218 t.daemon = True # so if this fails, we don't hang Python at shutdown
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000219 t.start()
220 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000221 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000222
223 # Try a thread id that doesn't make sense.
224 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000225 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000226 result = set_async_exc(ctypes.c_long(-1), exception)
227 self.assertEqual(result, 0) # no thread states modified
228
229 # Now raise an exception in the worker thread.
230 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000231 print(" waiting for worker thread to get started")
Benjamin Petersond23f8222009-04-05 19:13:16 +0000232 ret = worker_started.wait()
233 self.assertTrue(ret)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000234 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000235 print(" verifying worker hasn't exited")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000236 self.assertTrue(not t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000237 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000238 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000239 result = set_async_exc(ctypes.c_long(t.id), exception)
240 self.assertEqual(result, 1) # one thread state modified
241 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000242 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000243 worker_saw_exception.wait(timeout=10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000244 self.assertTrue(t.finished)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000246 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247 if t.finished:
248 t.join()
249 # else the thread is still running, and we have no way to kill it
250
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000251 def test_limbo_cleanup(self):
252 # Issue 7481: Failure to start thread should cleanup the limbo map.
253 def fail_new_thread(*args):
254 raise threading.ThreadError()
255 _start_new_thread = threading._start_new_thread
256 threading._start_new_thread = fail_new_thread
257 try:
258 t = threading.Thread(target=lambda: None)
Gregory P. Smithf50f1682010-03-01 03:13:36 +0000259 self.assertRaises(threading.ThreadError, t.start)
260 self.assertFalse(
261 t in threading._limbo,
262 "Failed to cleanup _limbo map on failure of Thread.start().")
Gregory P. Smith3fdd9642010-02-28 18:57:46 +0000263 finally:
264 threading._start_new_thread = _start_new_thread
265
Christian Heimes7d2ff882007-11-30 14:35:04 +0000266 def test_finalize_runnning_thread(self):
267 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
268 # very late on python exit: on deallocation of a running thread for
269 # example.
270 try:
271 import ctypes
272 except ImportError:
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000273 raise unittest.SkipTest("cannot import ctypes")
Christian Heimes7d2ff882007-11-30 14:35:04 +0000274
275 import subprocess
276 rc = subprocess.call([sys.executable, "-c", """if 1:
Georg Brandl2067bfd2008-05-25 13:05:15 +0000277 import ctypes, sys, time, _thread
Christian Heimes7d2ff882007-11-30 14:35:04 +0000278
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000279 # This lock is used as a simple event variable.
Georg Brandl2067bfd2008-05-25 13:05:15 +0000280 ready = _thread.allocate_lock()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000281 ready.acquire()
282
Christian Heimes7d2ff882007-11-30 14:35:04 +0000283 # Module globals are cleared before __del__ is run
284 # So we save the functions in class dict
285 class C:
286 ensure = ctypes.pythonapi.PyGILState_Ensure
287 release = ctypes.pythonapi.PyGILState_Release
288 def __del__(self):
289 state = self.ensure()
290 self.release(state)
291
292 def waitingThread():
293 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000294 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000295 time.sleep(100)
296
Georg Brandl2067bfd2008-05-25 13:05:15 +0000297 _thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000298 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000299 sys.exit(42)
300 """])
301 self.assertEqual(rc, 42)
302
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000303 def test_finalize_with_trace(self):
304 # Issue1733757
305 # Avoid a deadlock when sys.settrace steps into threading._shutdown
306 import subprocess
Antoine Pitrou7c087442010-09-19 23:28:30 +0000307 p = subprocess.Popen([sys.executable, "-c", """if 1:
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000308 import sys, threading
309
310 # A deadlock-killer, to prevent the
311 # testsuite to hang forever
312 def killer():
313 import os, time
314 time.sleep(2)
315 print('program blocked; aborting')
316 os._exit(2)
317 t = threading.Thread(target=killer)
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000318 t.daemon = True
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000319 t.start()
320
321 # This is the trace function
322 def func(frame, event, arg):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000323 threading.current_thread()
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000324 return func
325
326 sys.settrace(func)
Antoine Pitrou7c087442010-09-19 23:28:30 +0000327 """],
328 stdout=subprocess.PIPE,
329 stderr=subprocess.PIPE)
Brian Curtinde11b182010-11-05 17:22:46 +0000330 self.addCleanup(p.stdout.close)
331 self.addCleanup(p.stderr.close)
Antoine Pitrou7c087442010-09-19 23:28:30 +0000332 stdout, stderr = p.communicate()
333 rc = p.returncode
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000334 self.assertFalse(rc == 2, "interpreted was blocked")
Antoine Pitrou7c087442010-09-19 23:28:30 +0000335 self.assertTrue(rc == 0,
336 "Unexpected error: " + ascii(stderr))
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000337
Antoine Pitrou011bd622009-10-20 21:52:47 +0000338 def test_join_nondaemon_on_shutdown(self):
339 # Issue 1722344
340 # Raising SystemExit skipped threading._shutdown
341 import subprocess
342 p = subprocess.Popen([sys.executable, "-c", """if 1:
343 import threading
344 from time import sleep
345
346 def child():
347 sleep(1)
348 # As a non-daemon thread we SHOULD wake up and nothing
349 # should be torn down yet
350 print("Woke up, sleep function is:", sleep)
351
352 threading.Thread(target=child).start()
353 raise SystemExit
354 """],
355 stdout=subprocess.PIPE,
356 stderr=subprocess.PIPE)
Brian Curtinde11b182010-11-05 17:22:46 +0000357 self.addCleanup(p.stdout.close)
358 self.addCleanup(p.stderr.close)
Antoine Pitrou011bd622009-10-20 21:52:47 +0000359 stdout, stderr = p.communicate()
Antoine Pitrou899d1c62009-10-23 21:55:36 +0000360 self.assertEqual(stdout.strip(),
361 b"Woke up, sleep function is: <built-in function sleep>")
Antoine Pitrou62f68ed2010-08-04 11:48:56 +0000362 stderr = strip_python_stderr(stderr)
Antoine Pitrou011bd622009-10-20 21:52:47 +0000363 self.assertEqual(stderr, b"")
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000364
Christian Heimes1af737c2008-01-23 08:24:23 +0000365 def test_enumerate_after_join(self):
366 # Try hard to trigger #1703448: a thread is still returned in
367 # threading.enumerate() after it has been join()ed.
368 enum = threading.enumerate
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000369 old_interval = sys.getswitchinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000370 try:
Jeffrey Yasskinca674122008-03-29 05:06:52 +0000371 for i in range(1, 100):
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000372 sys.setswitchinterval(i * 0.0002)
Christian Heimes1af737c2008-01-23 08:24:23 +0000373 t = threading.Thread(target=lambda: None)
374 t.start()
375 t.join()
376 l = enum()
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000377 self.assertNotIn(t, l,
Christian Heimes1af737c2008-01-23 08:24:23 +0000378 "#1703448 triggered after %d trials: %s" % (i, l))
379 finally:
Antoine Pitrouc3b07572009-11-13 22:19:19 +0000380 sys.setswitchinterval(old_interval)
Christian Heimes1af737c2008-01-23 08:24:23 +0000381
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000382 def test_no_refcycle_through_target(self):
383 class RunSelfFunction(object):
384 def __init__(self, should_raise):
385 # The links in this refcycle from Thread back to self
386 # should be cleaned up when the thread completes.
387 self.should_raise = should_raise
388 self.thread = threading.Thread(target=self._run,
389 args=(self,),
390 kwargs={'yet_another':self})
391 self.thread.start()
392
393 def _run(self, other_ref, yet_another):
394 if self.should_raise:
395 raise SystemExit
396
397 cyclic_object = RunSelfFunction(should_raise=False)
398 weak_cyclic_object = weakref.ref(cyclic_object)
399 cyclic_object.thread.join()
400 del cyclic_object
Ezio Melottib3aedd42010-11-20 19:04:17 +0000401 self.assertEqual(None, weak_cyclic_object(),
402 msg=('%d references still around' %
403 sys.getrefcount(weak_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000404
405 raising_cyclic_object = RunSelfFunction(should_raise=True)
406 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
407 raising_cyclic_object.thread.join()
408 del raising_cyclic_object
Ezio Melottib3aedd42010-11-20 19:04:17 +0000409 self.assertEqual(None, weak_raising_cyclic_object(),
410 msg=('%d references still around' %
411 sys.getrefcount(weak_raising_cyclic_object())))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000412
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000413 def test_old_threading_api(self):
414 # Just a quick sanity check to make sure the old method names are
415 # still present
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000416 t = threading.Thread()
Benjamin Petersonb3085c92008-09-01 23:09:31 +0000417 t.isDaemon()
418 t.setDaemon(True)
419 t.getName()
420 t.setName("name")
421 t.isAlive()
422 e = threading.Event()
423 e.isSet()
424 threading.activeCount()
Benjamin Petersonf0923f52008-08-18 22:10:13 +0000425
Brian Curtin81a4a6a2010-07-23 16:30:10 +0000426 def test_repr_daemon(self):
427 t = threading.Thread()
428 self.assertFalse('daemon' in repr(t))
429 t.daemon = True
430 self.assertTrue('daemon' in repr(t))
Brett Cannon3f5f2262010-07-23 15:50:52 +0000431
Christian Heimes1af737c2008-01-23 08:24:23 +0000432
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000433class ThreadJoinOnShutdown(BaseTestCase):
Jesse Nollera8513972008-07-17 16:49:17 +0000434
435 def _run_and_join(self, script):
436 script = """if 1:
437 import sys, os, time, threading
438
439 # a thread, which waits for the main program to terminate
440 def joiningfunc(mainthread):
441 mainthread.join()
442 print('end of thread')
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000443 # stdout is fully buffered because not a tty, we have to flush
444 # before exit.
445 sys.stdout.flush()
Jesse Nollera8513972008-07-17 16:49:17 +0000446 \n""" + script
447
448 import subprocess
449 p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
450 rc = p.wait()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000451 data = p.stdout.read().decode().replace('\r', '')
Brian Curtinb68928b2010-11-02 03:59:09 +0000452 p.stdout.close()
Benjamin Petersonad703dc2008-07-17 17:02:57 +0000453 self.assertEqual(data, "end of main\nend of thread\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000454 self.assertFalse(rc == 2, "interpreter was blocked")
455 self.assertTrue(rc == 0, "Unexpected error")
Jesse Nollera8513972008-07-17 16:49:17 +0000456
457 def test_1_join_on_shutdown(self):
458 # The usual case: on exit, wait for a non-daemon thread
459 script = """if 1:
460 import os
461 t = threading.Thread(target=joiningfunc,
462 args=(threading.current_thread(),))
463 t.start()
464 time.sleep(0.1)
465 print('end of main')
466 """
467 self._run_and_join(script)
468
469
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000470 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Jesse Nollera8513972008-07-17 16:49:17 +0000471 def test_2_join_in_forked_process(self):
472 # Like the test above, but from a forked interpreter
Jesse Nollera8513972008-07-17 16:49:17 +0000473 script = """if 1:
474 childpid = os.fork()
475 if childpid != 0:
476 os.waitpid(childpid, 0)
477 sys.exit(0)
478
479 t = threading.Thread(target=joiningfunc,
480 args=(threading.current_thread(),))
481 t.start()
482 print('end of main')
483 """
484 self._run_and_join(script)
485
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000486 @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
Antoine Pitrou5fe291f2008-09-06 23:00:03 +0000487 def test_3_join_in_forked_from_thread(self):
Jesse Nollera8513972008-07-17 16:49:17 +0000488 # Like the test above, but fork() was called from a worker thread
489 # In the forked process, the main Thread object must be marked as stopped.
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000490
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +0000491 # Skip platforms with known problems forking from a worker thread.
492 # See http://bugs.python.org/issue3863.
Gregory P. Smithfeedda22010-10-17 03:09:12 +0000493 if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
494 'os2emx'):
Alexandre Vassalotti93f2cd22009-07-22 04:54:52 +0000495 raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
Jesse Nollera8513972008-07-17 16:49:17 +0000496 script = """if 1:
497 main_thread = threading.current_thread()
498 def worker():
499 childpid = os.fork()
500 if childpid != 0:
501 os.waitpid(childpid, 0)
502 sys.exit(0)
503
504 t = threading.Thread(target=joiningfunc,
505 args=(main_thread,))
506 print('end of main')
507 t.start()
508 t.join() # Should not block: main_thread is already stopped
509
510 w = threading.Thread(target=worker)
511 w.start()
512 """
513 self._run_and_join(script)
514
515
Antoine Pitroub0e9bd42009-10-27 20:05:26 +0000516class ThreadingExceptionTests(BaseTestCase):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000517 # A RuntimeError should be raised if Thread.start() is called
518 # multiple times.
519 def test_start_thread_again(self):
520 thread = threading.Thread()
521 thread.start()
522 self.assertRaises(RuntimeError, thread.start)
523
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000524 def test_joining_current_thread(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000525 current_thread = threading.current_thread()
526 self.assertRaises(RuntimeError, current_thread.join);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000527
528 def test_joining_inactive_thread(self):
529 thread = threading.Thread()
530 self.assertRaises(RuntimeError, thread.join)
531
532 def test_daemonize_active_thread(self):
533 thread = threading.Thread()
534 thread.start()
Benjamin Petersonfdbea962008-08-18 17:33:47 +0000535 self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000536
537
Antoine Pitrou557934f2009-11-06 22:41:14 +0000538class LockTests(lock_tests.LockTests):
539 locktype = staticmethod(threading.Lock)
540
Antoine Pitrou434736a2009-11-10 18:46:01 +0000541class PyRLockTests(lock_tests.RLockTests):
542 locktype = staticmethod(threading._PyRLock)
543
544class CRLockTests(lock_tests.RLockTests):
545 locktype = staticmethod(threading._CRLock)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000546
547class EventTests(lock_tests.EventTests):
548 eventtype = staticmethod(threading.Event)
549
550class ConditionAsRLockTests(lock_tests.RLockTests):
551 # An Condition uses an RLock by default and exports its API.
552 locktype = staticmethod(threading.Condition)
553
554class ConditionTests(lock_tests.ConditionTests):
555 condtype = staticmethod(threading.Condition)
556
557class SemaphoreTests(lock_tests.SemaphoreTests):
558 semtype = staticmethod(threading.Semaphore)
559
560class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
561 semtype = staticmethod(threading.BoundedSemaphore)
562
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000563class BarrierTests(lock_tests.BarrierTests):
564 barriertype = staticmethod(threading.Barrier)
Antoine Pitrou557934f2009-11-06 22:41:14 +0000565
Tim Peters84d54892005-01-08 06:03:17 +0000566def test_main():
Antoine Pitrou434736a2009-11-10 18:46:01 +0000567 test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
Antoine Pitrou557934f2009-11-06 22:41:14 +0000568 ConditionAsRLockTests, ConditionTests,
569 SemaphoreTests, BoundedSemaphoreTests,
570 ThreadTests,
571 ThreadJoinOnShutdown,
572 ThreadingExceptionTests,
Kristján Valur Jónsson3be00032010-10-28 09:43:10 +0000573 BarrierTests
Antoine Pitrou557934f2009-11-06 22:41:14 +0000574 )
Tim Peters84d54892005-01-08 06:03:17 +0000575
576if __name__ == "__main__":
577 test_main()