blob: 3d5c12076b8acce9790d84a725454e02c76fb9da [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):
Tim Peters02035bc2001-08-20 21:45:19 +000033 delay = random.random() * 2
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
37 self.sema.acquire()
38
39 self.mutex.acquire()
40 self.nrunning.inc()
Skip Montanaro4533f602001-08-20 20:28:48 +000041 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000042 print(self.nrunning.get(), 'tasks are running')
Tim Peters84d54892005-01-08 06:03:17 +000043 self.testcase.assert_(self.nrunning.get() <= 3)
44 self.mutex.release()
45
Skip Montanaro4533f602001-08-20 20:28:48 +000046 time.sleep(delay)
47 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000048 print('task', self.getName(), 'done')
Tim Peters84d54892005-01-08 06:03:17 +000049
50 self.mutex.acquire()
51 self.nrunning.dec()
52 self.testcase.assert_(self.nrunning.get() >= 0)
Skip Montanaro4533f602001-08-20 20:28:48 +000053 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000054 print(self.getName(), 'is finished.', self.nrunning.get(), \
55 'tasks are running')
Tim Peters84d54892005-01-08 06:03:17 +000056 self.mutex.release()
Skip Montanaro4533f602001-08-20 20:28:48 +000057
Tim Peters84d54892005-01-08 06:03:17 +000058 self.sema.release()
Skip Montanaro4533f602001-08-20 20:28:48 +000059
Tim Peters84d54892005-01-08 06:03:17 +000060class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000061
Tim Peters84d54892005-01-08 06:03:17 +000062 # Create a bunch of threads, let each do some work, wait until all are
63 # done.
64 def test_various_ops(self):
65 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
66 # times about 1 second per clump).
67 NUMTASKS = 10
68
69 # no more than 3 of the 10 can run at once
70 sema = threading.BoundedSemaphore(value=3)
71 mutex = threading.RLock()
72 numrunning = Counter()
73
74 threads = []
75
76 for i in range(NUMTASKS):
77 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
78 threads.append(t)
79 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)
85 self.assert_(not t.isAlive())
Tim Peters84d54892005-01-08 06:03:17 +000086 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000087 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000088 self.assertEqual(numrunning.get(), 0)
89
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090 # run with a small(ish) thread stack size (256kB)
91 def test_various_ops_small_stack(self):
92 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000093 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094 try:
95 threading.stack_size(262144)
96 except thread.error:
97 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000098 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099 return
100 self.test_various_ops()
101 threading.stack_size(0)
102
103 # run with a large thread stack size (1MB)
104 def test_various_ops_large_stack(self):
105 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000106 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107 try:
108 threading.stack_size(0x100000)
109 except thread.error:
110 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000111 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112 return
113 self.test_various_ops()
114 threading.stack_size(0)
115
Tim Peters711906e2005-01-08 07:30:42 +0000116 def test_foreign_thread(self):
117 # Check that a "foreign" thread can use the threading module.
118 def f(mutex):
119 # Acquiring an RLock forces an entry for the foreign
120 # thread to get made in the threading._active map.
121 r = threading.RLock()
122 r.acquire()
123 r.release()
124 mutex.release()
125
126 mutex = threading.Lock()
127 mutex.acquire()
128 tid = thread.start_new_thread(f, (mutex,))
129 # Wait for the thread to finish.
130 mutex.acquire()
131 self.assert_(tid in threading._active)
132 self.assert_(isinstance(threading._active[tid],
133 threading._DummyThread))
134 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000135
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000136 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
137 # exposed at the Python level. This test relies on ctypes to get at it.
138 def test_PyThreadState_SetAsyncExc(self):
139 try:
140 import ctypes
141 except ImportError:
142 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000143 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000144 return # can't do anything
145
146 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
147
148 class AsyncExc(Exception):
149 pass
150
151 exception = ctypes.py_object(AsyncExc)
152
153 # `worker_started` is set by the thread when it's inside a try/except
154 # block waiting to catch the asynchronously set AsyncExc exception.
155 # `worker_saw_exception` is set by the thread upon catching that
156 # exception.
157 worker_started = threading.Event()
158 worker_saw_exception = threading.Event()
159
160 class Worker(threading.Thread):
161 def run(self):
162 self.id = thread.get_ident()
163 self.finished = False
164
165 try:
166 while True:
167 worker_started.set()
168 time.sleep(0.1)
169 except AsyncExc:
170 self.finished = True
171 worker_saw_exception.set()
172
173 t = Worker()
174 t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
175 t.start()
176 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000177 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178
179 # Try a thread id that doesn't make sense.
180 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000181 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000182 result = set_async_exc(ctypes.c_long(-1), exception)
183 self.assertEqual(result, 0) # no thread states modified
184
185 # Now raise an exception in the worker thread.
186 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000187 print(" waiting for worker thread to get started")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000188 worker_started.wait()
189 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000190 print(" verifying worker hasn't exited")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000191 self.assert_(not t.finished)
192 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000193 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000194 result = set_async_exc(ctypes.c_long(t.id), exception)
195 self.assertEqual(result, 1) # one thread state modified
196 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000197 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000198 worker_saw_exception.wait(timeout=10)
199 self.assert_(t.finished)
200 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000201 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000202 if t.finished:
203 t.join()
204 # else the thread is still running, and we have no way to kill it
205
Christian Heimes7d2ff882007-11-30 14:35:04 +0000206 def test_finalize_runnning_thread(self):
207 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
208 # very late on python exit: on deallocation of a running thread for
209 # example.
210 try:
211 import ctypes
212 except ImportError:
213 if verbose:
214 print("test_finalize_with_runnning_thread can't import ctypes")
215 return # can't do anything
216
217 import subprocess
218 rc = subprocess.call([sys.executable, "-c", """if 1:
219 import ctypes, sys, time, thread
220
221 # Module globals are cleared before __del__ is run
222 # So we save the functions in class dict
223 class C:
224 ensure = ctypes.pythonapi.PyGILState_Ensure
225 release = ctypes.pythonapi.PyGILState_Release
226 def __del__(self):
227 state = self.ensure()
228 self.release(state)
229
230 def waitingThread():
231 x = C()
232 time.sleep(100)
233
234 thread.start_new_thread(waitingThread, ())
235 time.sleep(1) # be sure the other thread is waiting
236 sys.exit(42)
237 """])
238 self.assertEqual(rc, 42)
239
Christian Heimes1af737c2008-01-23 08:24:23 +0000240 def test_enumerate_after_join(self):
241 # Try hard to trigger #1703448: a thread is still returned in
242 # threading.enumerate() after it has been join()ed.
243 enum = threading.enumerate
244 old_interval = sys.getcheckinterval()
245 sys.setcheckinterval(1)
246 try:
247 for i in range(1, 1000):
248 t = threading.Thread(target=lambda: None)
249 t.start()
250 t.join()
251 l = enum()
252 self.assertFalse(t in l,
253 "#1703448 triggered after %d trials: %s" % (i, l))
254 finally:
255 sys.setcheckinterval(old_interval)
256
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000257 def test_no_refcycle_through_target(self):
258 class RunSelfFunction(object):
259 def __init__(self, should_raise):
260 # The links in this refcycle from Thread back to self
261 # should be cleaned up when the thread completes.
262 self.should_raise = should_raise
263 self.thread = threading.Thread(target=self._run,
264 args=(self,),
265 kwargs={'yet_another':self})
266 self.thread.start()
267
268 def _run(self, other_ref, yet_another):
269 if self.should_raise:
270 raise SystemExit
271
272 cyclic_object = RunSelfFunction(should_raise=False)
273 weak_cyclic_object = weakref.ref(cyclic_object)
274 cyclic_object.thread.join()
275 del cyclic_object
276 self.assertEquals(None, weak_cyclic_object())
277
278 raising_cyclic_object = RunSelfFunction(should_raise=True)
279 weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
280 raising_cyclic_object.thread.join()
281 del raising_cyclic_object
282 self.assertEquals(None, weak_raising_cyclic_object())
283
Christian Heimes1af737c2008-01-23 08:24:23 +0000284
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000285class ThreadingExceptionTests(unittest.TestCase):
286 # A RuntimeError should be raised if Thread.start() is called
287 # multiple times.
288 def test_start_thread_again(self):
289 thread = threading.Thread()
290 thread.start()
291 self.assertRaises(RuntimeError, thread.start)
292
293 def test_releasing_unacquired_rlock(self):
294 rlock = threading.RLock()
295 self.assertRaises(RuntimeError, rlock.release)
296
297 def test_waiting_on_unacquired_condition(self):
298 cond = threading.Condition()
299 self.assertRaises(RuntimeError, cond.wait)
300
301 def test_notify_on_unacquired_condition(self):
302 cond = threading.Condition()
303 self.assertRaises(RuntimeError, cond.notify)
304
305 def test_semaphore_with_negative_value(self):
306 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000307 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000308
309 def test_joining_current_thread(self):
310 currentThread = threading.currentThread()
311 self.assertRaises(RuntimeError, currentThread.join);
312
313 def test_joining_inactive_thread(self):
314 thread = threading.Thread()
315 self.assertRaises(RuntimeError, thread.join)
316
317 def test_daemonize_active_thread(self):
318 thread = threading.Thread()
319 thread.start()
320 self.assertRaises(RuntimeError, thread.setDaemon, True)
321
322
Tim Peters84d54892005-01-08 06:03:17 +0000323def test_main():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000324 test.test_support.run_unittest(ThreadTests,
325 ThreadingExceptionTests)
Tim Peters84d54892005-01-08 06:03:17 +0000326
327if __name__ == "__main__":
328 test_main()