blob: 1ce595027ebdd9488dc98e7e011f0130399d394e [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
Skip Montanaro4533f602001-08-20 20:28:48 +000011
Tim Peters84d54892005-01-08 06:03:17 +000012# A trivial mutable counter.
13class Counter(object):
14 def __init__(self):
15 self.value = 0
16 def inc(self):
17 self.value += 1
18 def dec(self):
19 self.value -= 1
20 def get(self):
21 return self.value
Skip Montanaro4533f602001-08-20 20:28:48 +000022
23class TestThread(threading.Thread):
Tim Peters84d54892005-01-08 06:03:17 +000024 def __init__(self, name, testcase, sema, mutex, nrunning):
25 threading.Thread.__init__(self, name=name)
26 self.testcase = testcase
27 self.sema = sema
28 self.mutex = mutex
29 self.nrunning = nrunning
30
Skip Montanaro4533f602001-08-20 20:28:48 +000031 def run(self):
Tim Peters02035bc2001-08-20 21:45:19 +000032 delay = random.random() * 2
Skip Montanaro4533f602001-08-20 20:28:48 +000033 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000034 print('task', self.getName(), 'will run for', delay, 'sec')
Tim Peters84d54892005-01-08 06:03:17 +000035
36 self.sema.acquire()
37
38 self.mutex.acquire()
39 self.nrunning.inc()
Skip Montanaro4533f602001-08-20 20:28:48 +000040 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000041 print(self.nrunning.get(), 'tasks are running')
Tim Peters84d54892005-01-08 06:03:17 +000042 self.testcase.assert_(self.nrunning.get() <= 3)
43 self.mutex.release()
44
Skip Montanaro4533f602001-08-20 20:28:48 +000045 time.sleep(delay)
46 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000047 print('task', self.getName(), 'done')
Tim Peters84d54892005-01-08 06:03:17 +000048
49 self.mutex.acquire()
50 self.nrunning.dec()
51 self.testcase.assert_(self.nrunning.get() >= 0)
Skip Montanaro4533f602001-08-20 20:28:48 +000052 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000053 print(self.getName(), 'is finished.', self.nrunning.get(), \
54 'tasks are running')
Tim Peters84d54892005-01-08 06:03:17 +000055 self.mutex.release()
Skip Montanaro4533f602001-08-20 20:28:48 +000056
Tim Peters84d54892005-01-08 06:03:17 +000057 self.sema.release()
Skip Montanaro4533f602001-08-20 20:28:48 +000058
Tim Peters84d54892005-01-08 06:03:17 +000059class ThreadTests(unittest.TestCase):
Skip Montanaro4533f602001-08-20 20:28:48 +000060
Tim Peters84d54892005-01-08 06:03:17 +000061 # Create a bunch of threads, let each do some work, wait until all are
62 # done.
63 def test_various_ops(self):
64 # This takes about n/3 seconds to run (about n/3 clumps of tasks,
65 # times about 1 second per clump).
66 NUMTASKS = 10
67
68 # no more than 3 of the 10 can run at once
69 sema = threading.BoundedSemaphore(value=3)
70 mutex = threading.RLock()
71 numrunning = Counter()
72
73 threads = []
74
75 for i in range(NUMTASKS):
76 t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
77 threads.append(t)
78 t.start()
79
80 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000081 print('waiting for all tasks to complete')
Tim Peters84d54892005-01-08 06:03:17 +000082 for t in threads:
Tim Peters711906e2005-01-08 07:30:42 +000083 t.join(NUMTASKS)
84 self.assert_(not t.isAlive())
Tim Peters84d54892005-01-08 06:03:17 +000085 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000086 print('all tasks done')
Tim Peters84d54892005-01-08 06:03:17 +000087 self.assertEqual(numrunning.get(), 0)
88
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089 # run with a small(ish) thread stack size (256kB)
90 def test_various_ops_small_stack(self):
91 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000092 print('with 256kB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000093 try:
94 threading.stack_size(262144)
95 except thread.error:
96 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000097 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000098 return
99 self.test_various_ops()
100 threading.stack_size(0)
101
102 # run with a large thread stack size (1MB)
103 def test_various_ops_large_stack(self):
104 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000105 print('with 1MB thread stack size...')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106 try:
107 threading.stack_size(0x100000)
108 except thread.error:
109 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000110 print('platform does not support changing thread stack size')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000111 return
112 self.test_various_ops()
113 threading.stack_size(0)
114
Tim Peters711906e2005-01-08 07:30:42 +0000115 def test_foreign_thread(self):
116 # Check that a "foreign" thread can use the threading module.
117 def f(mutex):
118 # Acquiring an RLock forces an entry for the foreign
119 # thread to get made in the threading._active map.
120 r = threading.RLock()
121 r.acquire()
122 r.release()
123 mutex.release()
124
125 mutex = threading.Lock()
126 mutex.acquire()
127 tid = thread.start_new_thread(f, (mutex,))
128 # Wait for the thread to finish.
129 mutex.acquire()
130 self.assert_(tid in threading._active)
131 self.assert_(isinstance(threading._active[tid],
132 threading._DummyThread))
133 del threading._active[tid]
Tim Peters84d54892005-01-08 06:03:17 +0000134
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000135 # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
136 # exposed at the Python level. This test relies on ctypes to get at it.
137 def test_PyThreadState_SetAsyncExc(self):
138 try:
139 import ctypes
140 except ImportError:
141 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000142 print("test_PyThreadState_SetAsyncExc can't import ctypes")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000143 return # can't do anything
144
145 set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
146
147 class AsyncExc(Exception):
148 pass
149
150 exception = ctypes.py_object(AsyncExc)
151
152 # `worker_started` is set by the thread when it's inside a try/except
153 # block waiting to catch the asynchronously set AsyncExc exception.
154 # `worker_saw_exception` is set by the thread upon catching that
155 # exception.
156 worker_started = threading.Event()
157 worker_saw_exception = threading.Event()
158
159 class Worker(threading.Thread):
160 def run(self):
161 self.id = thread.get_ident()
162 self.finished = False
163
164 try:
165 while True:
166 worker_started.set()
167 time.sleep(0.1)
168 except AsyncExc:
169 self.finished = True
170 worker_saw_exception.set()
171
172 t = Worker()
173 t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
174 t.start()
175 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000176 print(" started worker thread")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000177
178 # Try a thread id that doesn't make sense.
179 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000180 print(" trying nonsensical thread id")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000181 result = set_async_exc(ctypes.c_long(-1), exception)
182 self.assertEqual(result, 0) # no thread states modified
183
184 # Now raise an exception in the worker thread.
185 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000186 print(" waiting for worker thread to get started")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000187 worker_started.wait()
188 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000189 print(" verifying worker hasn't exited")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190 self.assert_(not t.finished)
191 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000192 print(" attempting to raise asynch exception in worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000193 result = set_async_exc(ctypes.c_long(t.id), exception)
194 self.assertEqual(result, 1) # one thread state modified
195 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000196 print(" waiting for worker to say it caught the exception")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197 worker_saw_exception.wait(timeout=10)
198 self.assert_(t.finished)
199 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000200 print(" all OK -- joining worker")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000201 if t.finished:
202 t.join()
203 # else the thread is still running, and we have no way to kill it
204
Christian Heimes7d2ff882007-11-30 14:35:04 +0000205 def test_finalize_runnning_thread(self):
206 # Issue 1402: the PyGILState_Ensure / _Release functions may be called
207 # very late on python exit: on deallocation of a running thread for
208 # example.
209 try:
210 import ctypes
211 except ImportError:
212 if verbose:
213 print("test_finalize_with_runnning_thread can't import ctypes")
214 return # can't do anything
215
216 import subprocess
217 rc = subprocess.call([sys.executable, "-c", """if 1:
218 import ctypes, sys, time, thread
219
220 # Module globals are cleared before __del__ is run
221 # So we save the functions in class dict
222 class C:
223 ensure = ctypes.pythonapi.PyGILState_Ensure
224 release = ctypes.pythonapi.PyGILState_Release
225 def __del__(self):
226 state = self.ensure()
227 self.release(state)
228
229 def waitingThread():
230 x = C()
231 time.sleep(100)
232
233 thread.start_new_thread(waitingThread, ())
234 time.sleep(1) # be sure the other thread is waiting
235 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()
244 sys.setcheckinterval(1)
245 try:
246 for i in range(1, 1000):
247 t = threading.Thread(target=lambda: None)
248 t.start()
249 t.join()
250 l = enum()
251 self.assertFalse(t in l,
252 "#1703448 triggered after %d trials: %s" % (i, l))
253 finally:
254 sys.setcheckinterval(old_interval)
255
256
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000257class ThreadingExceptionTests(unittest.TestCase):
258 # A RuntimeError should be raised if Thread.start() is called
259 # multiple times.
260 def test_start_thread_again(self):
261 thread = threading.Thread()
262 thread.start()
263 self.assertRaises(RuntimeError, thread.start)
264
265 def test_releasing_unacquired_rlock(self):
266 rlock = threading.RLock()
267 self.assertRaises(RuntimeError, rlock.release)
268
269 def test_waiting_on_unacquired_condition(self):
270 cond = threading.Condition()
271 self.assertRaises(RuntimeError, cond.wait)
272
273 def test_notify_on_unacquired_condition(self):
274 cond = threading.Condition()
275 self.assertRaises(RuntimeError, cond.notify)
276
277 def test_semaphore_with_negative_value(self):
278 self.assertRaises(ValueError, threading.Semaphore, value = -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000279 self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000280
281 def test_joining_current_thread(self):
282 currentThread = threading.currentThread()
283 self.assertRaises(RuntimeError, currentThread.join);
284
285 def test_joining_inactive_thread(self):
286 thread = threading.Thread()
287 self.assertRaises(RuntimeError, thread.join)
288
289 def test_daemonize_active_thread(self):
290 thread = threading.Thread()
291 thread.start()
292 self.assertRaises(RuntimeError, thread.setDaemon, True)
293
294
Tim Peters84d54892005-01-08 06:03:17 +0000295def test_main():
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000296 test.test_support.run_unittest(ThreadTests,
297 ThreadingExceptionTests)
Tim Peters84d54892005-01-08 06:03:17 +0000298
299if __name__ == "__main__":
300 test_main()