blob: 67d9ed95374be1a223982f1ab1ff36c60b341a82 [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
Tim Peters84d54892005-01-08 06:03:17 +00003import test.test_support
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test.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
Tim Peters711906e2005-01-08 07:30:42 +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:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000035 print('task', self.getName(), 'will run for', delay, 'sec')
Tim Peters84d54892005-01-08 06:03:17 +000036
Christian Heimes4fbc72b2008-03-22 00:47:35 +000037 with self.sema:
38 with self.mutex:
39 self.nrunning.inc()
40 if verbose:
41 print(self.nrunning.get(), 'tasks are running')
42 self.testcase.assert_(self.nrunning.get() <= 3)
Tim Peters84d54892005-01-08 06:03:17 +000043
Christian Heimes4fbc72b2008-03-22 00:47:35 +000044 time.sleep(delay)
45 if verbose:
46 print('task', self.getName(), 'done')
47 with self.mutex:
48 self.nrunning.dec()
49 self.testcase.assert_(self.nrunning.get() >= 0)
50 if verbose:
51 print('%s is finished. %d tasks are running' %
52 self.getName(), self.nrunning.get())
Skip Montanaro4533f602001-08-20 20:28:48 +000053
Tim Peters84d54892005-01-08 06:03:17 +000054class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000055
Tim Peters84d54892005-01-08 06:03:17 +000056 # Create a bunch of threads, let each do some work, wait until all are
57 # done.
58 def test_various_ops(self):
59 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
60 # times about 1 second per clump).
61 NUMTASKS = 10
62
63 # no more than 3 of the 10 can run at once
64 sema = threading.BoundedSemaphore(value=3)
65 mutex = threading.RLock()
66 numrunning = Counter()
67
68 threads = []
69
70 for i in range(NUMTASKS):
71 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
72 threads.append(t)
73 t.start()
74
75 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000076 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000077 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000078 t.join(NUMTASKS)
79 self.assert_(not t.isAlive())
Tim Peters84d54892005-01-08 06:03:17 +000080 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000081 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000082 self.assertEqual(numrunning.get(), 0)
83
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084 # run with a small(ish) thread stack size (256kB)
85 def test_various_ops_small_stack(self):
86 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000087 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088 try:
89 threading.stack_size(262144)
90 except thread.error:
91 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000092 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000093 return
94 self.test_various_ops()
95 threading.stack_size(0)
96
97 # run with a large thread stack size (1MB)
98 def test_various_ops_large_stack(self):
99 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000100 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000101 try:
102 threading.stack_size(0x100000)
103 except thread.error:
104 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000105 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106 return
107 self.test_various_ops()
108 threading.stack_size(0)
109
Tim Peters711906e2005-01-08 07:30:42 +0000110 def test_foreign_thread(self):
111 # Check that a "foreign" thread can use the threading module.
112 def f(mutex):
113 # Acquiring an RLock forces an entry for the foreign
114 # thread to get made in the threading._active map.
115 r = threading.RLock()
116 r.acquire()
117 r.release()
118 mutex.release()
119
120 mutex = threading.Lock()
121 mutex.acquire()
122 tid = thread.start_new_thread(f, (mutex,))
123 # Wait for the thread to finish.
124 mutex.acquire()
125 self.assert_(tid in threading._active)
126 self.assert_(isinstance(threading._active[tid],
127 threading._DummyThread))
128 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000129
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000130 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
131 # exposed at the Python level. This test relies on ctypes to get at it.
132 def test_PyThreadState_SetAsyncExc(self):
133 try:
134 import ctypes
135 except ImportError:
136 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000137 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000138 return # can't do anything
139
140 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
141
142 class AsyncExc(Exception):
143 pass
144
145 exception = ctypes.py_object(AsyncExc)
146
147 # `worker_started` is set by the thread when it's inside a try/except
148 # block waiting to catch the asynchronously set AsyncExc exception.
149 # `worker_saw_exception` is set by the thread upon catching that
150 # exception.
151 worker_started = threading.Event()
152 worker_saw_exception = threading.Event()
153
154 class Worker(threading.Thread):
155 def run(self):
156 self.id = thread.get_ident()
157 self.finished = False
158
159 try:
160 while True:
161 worker_started.set()
162 time.sleep(0.1)
163 except AsyncExc:
164 self.finished = True
165 worker_saw_exception.set()
166
167 t = Worker()
168 t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
169 t.start()
170 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000171 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000172
173 # Try a thread id that doesn't make sense.
174 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000175 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000176 result = set_async_exc(ctypes.c_long(-1), exception)
177 self.assertEqual(result, 0) # no thread states modified
178
179 # Now raise an exception in the worker thread.
180 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000181 print(" waiting for worker thread to get started")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000182 worker_started.wait()
183 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000184 print(" verifying worker hasn't exited")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000185 self.assert_(not t.finished)
186 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000187 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000188 result = set_async_exc(ctypes.c_long(t.id), exception)
189 self.assertEqual(result, 1) # one thread state modified
190 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000191 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000192 worker_saw_exception.wait(timeout=10)
193 self.assert_(t.finished)
194 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000195 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000196 if t.finished:
197 t.join()
198 # else the thread is still running, and we have no way to kill it
199
Christian Heimes7d2ff882007-11-30 14:35:04 +0000200 def test_finalize_runnning_thread(self):
201 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
202 # very late on python exit: on deallocation of a running thread for
203 # example.
204 try:
205 import ctypes
206 except ImportError:
207 if verbose:
208 print("test_finalize_with_runnning_thread can't import ctypes")
209 return # can't do anything
210
211 import subprocess
212 rc = subprocess.call([sys.executable, "-c", """if 1:
213 import ctypes, sys, time, thread
214
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000215 # This lock is used as a simple event variable.
216 ready = thread.allocate_lock()
217 ready.acquire()
218
Christian Heimes7d2ff882007-11-30 14:35:04 +0000219 # Module globals are cleared before __del__ is run
220 # So we save the functions in class dict
221 class C:
222 ensure = ctypes.pythonapi.PyGILState_Ensure
223 release = ctypes.pythonapi.PyGILState_Release
224 def __del__(self):
225 state = self.ensure()
226 self.release(state)
227
228 def waitingThread():
229 x = C()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000230 ready.release()
Christian Heimes7d2ff882007-11-30 14:35:04 +0000231 time.sleep(100)
232
233 thread.start_new_thread(waitingThread, ())
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000234 ready.acquire() # Be sure the other thread is waiting.
Christian Heimes7d2ff882007-11-30 14:35:04 +0000235 sys.exit(42)
236 """])
237 self.assertEqual(rc, 42)
238
Christian Heimes1af737c2008-01-23 08:24:23 +0000239 def test_enumerate_after_join(self):
240 # Try hard to trigger #1703448: a thread is still returned in
241 # threading.enumerate() after it has been join()ed.
242 enum = threading.enumerate
243 old_interval = sys.getcheckinterval()
Christian Heimes1af737c2008-01-23 08:24:23 +0000244 try:
245 for i in range(1, 1000):
246 t = threading.Thread(target=lambda: None)
247 t.start()
248 t.join()
249 l = enum()
250 self.assertFalse(t in l,
251 "#1703448 triggered after %d trials: %s" % (i, l))
252 finally:
253 sys.setcheckinterval(old_interval)
254
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000255 def test_no_refcycle_through_target(self):
256 class RunSelfFunction(object):
257 def __init__(self, should_raise):
258 # The links in this refcycle from Thread back to self
259 # should be cleaned up when the thread completes.
260 self.should_raise = should_raise
261 self.thread = threading.Thread(target=self._run,
262 args=(self,),
263 kwargs={'yet_another':self})
264 self.thread.start()
265
266 def _run(self, other_ref, yet_another):
267 if self.should_raise:
268 raise SystemExit
269
270 cyclic_object = RunSelfFunction(should_raise=False)
271 weak_cyclic_object = weakref.ref(cyclic_object)
272 cyclic_object.thread.join()
273 del cyclic_object
274 self.assertEquals(None, weak_cyclic_object())
275
276 raising_cyclic_object = RunSelfFunction(should_raise=True)
277 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
278 raising_cyclic_object.thread.join()
279 del raising_cyclic_object
280 self.assertEquals(None, weak_raising_cyclic_object())
281
Christian Heimes1af737c2008-01-23 08:24:23 +0000282
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000283class ThreadingExceptionTests(unittest.TestCase):
284 # A RuntimeError should be raised if Thread.start() is called
285 # multiple times.
286 def test_start_thread_again(self):
287 thread = threading.Thread()
288 thread.start()
289 self.assertRaises(RuntimeError, thread.start)
290
291 def test_releasing_unacquired_rlock(self):
292 rlock = threading.RLock()
293 self.assertRaises(RuntimeError, rlock.release)
294
295 def test_waiting_on_unacquired_condition(self):
296 cond = threading.Condition()
297 self.assertRaises(RuntimeError, cond.wait)
298
299 def test_notify_on_unacquired_condition(self):
300 cond = threading.Condition()
301 self.assertRaises(RuntimeError, cond.notify)
302
303 def test_semaphore_with_negative_value(self):
304 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000305 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000306
307 def test_joining_current_thread(self):
308 currentThread = threading.currentThread()
309 self.assertRaises(RuntimeError, currentThread.join);
310
311 def test_joining_inactive_thread(self):
312 thread = threading.Thread()
313 self.assertRaises(RuntimeError, thread.join)
314
315 def test_daemonize_active_thread(self):
316 thread = threading.Thread()
317 thread.start()
318 self.assertRaises(RuntimeError, thread.setDaemon, True)
319
320
Tim Peters84d54892005-01-08 06:03:17 +0000321def test_main():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000322 test.test_support.run_unittest(ThreadTests,
323 ThreadingExceptionTests)
Tim Peters84d54892005-01-08 06:03:17 +0000324
325if __name__ == "__main__":
326 test_main()