blob: c8caa5ddff03a0477ddedd2f3cca975d83fa882a [file] [log] [blame]
Brett Cannon66865d22008-03-13 20:27:00 +00001import os
2import unittest
Guido van Rossumb26a1b41998-05-20 17:05:52 +00003import random
Brett Cannon66865d22008-03-13 20:27:00 +00004from test import test_support
Victor Stinner6a102812010-04-27 23:55:59 +00005thread = test_support.import_module('thread')
Guido van Rossumcc544171994-04-14 20:28:41 +00006import time
Gregory P. Smith9e5d1322010-03-01 01:22:39 +00007import sys
Antoine Pitrou59c44f32009-10-30 17:07:08 +00008import weakref
Guido van Rossumcc544171994-04-14 20:28:41 +00009
Antoine Pitrouc98efe02009-11-06 22:34:35 +000010from test import lock_tests
Guido van Rossumcc544171994-04-14 20:28:41 +000011
Brett Cannon66865d22008-03-13 20:27:00 +000012NUMTASKS = 10
13NUMTRIPS = 3
Guido van Rossumd3b68421994-05-23 12:17:36 +000014
Guido van Rossumcc544171994-04-14 20:28:41 +000015
Jeffrey Yasskina1458532008-03-18 04:56:06 +000016_print_mutex = thread.allocate_lock()
17
Brett Cannon66865d22008-03-13 20:27:00 +000018def verbose_print(arg):
19 """Helper function for printing out debugging output."""
20 if test_support.verbose:
Jeffrey Yasskina1458532008-03-18 04:56:06 +000021 with _print_mutex:
22 print arg
Guido van Rossumcc544171994-04-14 20:28:41 +000023
Guido van Rossumcc544171994-04-14 20:28:41 +000024
grzgrzgrz36924ed52017-05-15 21:01:07 +020025
Brett Cannon66865d22008-03-13 20:27:00 +000026class BasicThreadTest(unittest.TestCase):
Guido van Rossumd3b68421994-05-23 12:17:36 +000027
Brett Cannon66865d22008-03-13 20:27:00 +000028 def setUp(self):
29 self.done_mutex = thread.allocate_lock()
30 self.done_mutex.acquire()
31 self.running_mutex = thread.allocate_lock()
32 self.random_mutex = thread.allocate_lock()
Antoine Pitroub5cf8a02009-10-23 18:32:15 +000033 self.created = 0
Brett Cannon66865d22008-03-13 20:27:00 +000034 self.running = 0
35 self.next_ident = 0
36
grzgrzgrz36924ed52017-05-15 21:01:07 +020037 key = test_support.threading_setup()
38 self.addCleanup(test_support.threading_cleanup, *key)
39
Brett Cannon66865d22008-03-13 20:27:00 +000040
41class ThreadRunningTests(BasicThreadTest):
42
43 def newtask(self):
44 with self.running_mutex:
45 self.next_ident += 1
46 verbose_print("creating task %s" % self.next_ident)
47 thread.start_new_thread(self.task, (self.next_ident,))
Antoine Pitroub5cf8a02009-10-23 18:32:15 +000048 self.created += 1
Brett Cannon66865d22008-03-13 20:27:00 +000049 self.running += 1
50
51 def task(self, ident):
52 with self.random_mutex:
Jeffrey Yasskina1458532008-03-18 04:56:06 +000053 delay = random.random() / 10000.0
54 verbose_print("task %s will run for %sus" % (ident, round(delay*1e6)))
Brett Cannon66865d22008-03-13 20:27:00 +000055 time.sleep(delay)
56 verbose_print("task %s done" % ident)
57 with self.running_mutex:
58 self.running -= 1
Antoine Pitroub5cf8a02009-10-23 18:32:15 +000059 if self.created == NUMTASKS and self.running == 0:
Brett Cannon66865d22008-03-13 20:27:00 +000060 self.done_mutex.release()
61
62 def test_starting_threads(self):
63 # Basic test for thread creation.
64 for i in range(NUMTASKS):
65 self.newtask()
66 verbose_print("waiting for tasks to complete...")
67 self.done_mutex.acquire()
68 verbose_print("all tasks done")
69
70 def test_stack_size(self):
71 # Various stack size tests.
Florent Xicluna2e6d2622010-03-20 00:17:46 +000072 self.assertEqual(thread.stack_size(), 0, "initial stack size is not 0")
Brett Cannon66865d22008-03-13 20:27:00 +000073
74 thread.stack_size(0)
Florent Xicluna2e6d2622010-03-20 00:17:46 +000075 self.assertEqual(thread.stack_size(), 0, "stack_size not reset to default")
Brett Cannon66865d22008-03-13 20:27:00 +000076
Zachary Ware1f702212013-12-10 14:09:20 -060077 @unittest.skipIf(os.name not in ("nt", "os2", "posix"), 'test meant for nt, os2, and posix')
78 def test_nt_and_posix_stack_size(self):
Brett Cannon66865d22008-03-13 20:27:00 +000079 try:
80 thread.stack_size(4096)
81 except ValueError:
82 verbose_print("caught expected ValueError setting "
83 "stack_size(4096)")
84 except thread.error:
Zachary Ware1f702212013-12-10 14:09:20 -060085 self.skipTest("platform does not support changing thread stack "
86 "size")
Brett Cannon66865d22008-03-13 20:27:00 +000087
Zachary Ware1f702212013-12-10 14:09:20 -060088 fail_msg = "stack_size(%d) failed - should succeed"
89 for tss in (262144, 0x100000, 0):
90 thread.stack_size(tss)
91 self.assertEqual(thread.stack_size(), tss, fail_msg % tss)
92 verbose_print("successfully set stack_size(%d)" % tss)
Brett Cannon66865d22008-03-13 20:27:00 +000093
Zachary Ware1f702212013-12-10 14:09:20 -060094 for tss in (262144, 0x100000):
95 verbose_print("trying stack_size = (%d)" % tss)
96 self.next_ident = 0
97 self.created = 0
98 for i in range(NUMTASKS):
99 self.newtask()
Brett Cannon66865d22008-03-13 20:27:00 +0000100
Zachary Ware1f702212013-12-10 14:09:20 -0600101 verbose_print("waiting for all tasks to complete")
102 self.done_mutex.acquire()
103 verbose_print("all tasks done")
Brett Cannon66865d22008-03-13 20:27:00 +0000104
Zachary Ware1f702212013-12-10 14:09:20 -0600105 thread.stack_size(0)
Brett Cannon66865d22008-03-13 20:27:00 +0000106
Antoine Pitrou59c44f32009-10-30 17:07:08 +0000107 def test__count(self):
108 # Test the _count() function.
109 orig = thread._count()
110 mut = thread.allocate_lock()
111 mut.acquire()
112 started = []
113 def task():
114 started.append(None)
115 mut.acquire()
116 mut.release()
117 thread.start_new_thread(task, ())
118 while not started:
119 time.sleep(0.01)
Florent Xicluna2e6d2622010-03-20 00:17:46 +0000120 self.assertEqual(thread._count(), orig + 1)
Antoine Pitrou59c44f32009-10-30 17:07:08 +0000121 # Allow the task to finish.
122 mut.release()
123 # The only reliable way to be sure that the thread ended from the
124 # interpreter's point of view is to wait for the function object to be
125 # destroyed.
126 done = []
127 wr = weakref.ref(task, lambda _: done.append(None))
128 del task
129 while not done:
130 time.sleep(0.01)
Florent Xicluna2e6d2622010-03-20 00:17:46 +0000131 self.assertEqual(thread._count(), orig)
Antoine Pitrou59c44f32009-10-30 17:07:08 +0000132
Benjamin Petersonf73813a2012-04-02 11:15:17 -0400133 def test_save_exception_state_on_error(self):
134 # See issue #14474
135 def task():
136 started.release()
Benjamin Petersonf73813a2012-04-02 11:15:17 -0400137 raise SyntaxError
138 def mywrite(self, *args):
139 try:
140 raise ValueError
141 except ValueError:
142 pass
143 real_write(self, *args)
144 c = thread._count()
145 started = thread.allocate_lock()
146 with test_support.captured_output("stderr") as stderr:
147 real_write = stderr.write
148 stderr.write = mywrite
149 started.acquire()
150 thread.start_new_thread(task, ())
151 started.acquire()
152 while thread._count() > c:
Benjamin Peterson19e9beb2012-04-23 10:08:14 -0400153 time.sleep(0.01)
Benjamin Petersonf73813a2012-04-02 11:15:17 -0400154 self.assertIn("Traceback", stderr.getvalue())
155
Brett Cannon66865d22008-03-13 20:27:00 +0000156
157class Barrier:
158 def __init__(self, num_threads):
159 self.num_threads = num_threads
Fred Drake004d5e62000-10-23 17:22:08 +0000160 self.waiting = 0
Brett Cannon66865d22008-03-13 20:27:00 +0000161 self.checkin_mutex = thread.allocate_lock()
162 self.checkout_mutex = thread.allocate_lock()
163 self.checkout_mutex.acquire()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000164
Fred Drake004d5e62000-10-23 17:22:08 +0000165 def enter(self):
Brett Cannon66865d22008-03-13 20:27:00 +0000166 self.checkin_mutex.acquire()
Fred Drake004d5e62000-10-23 17:22:08 +0000167 self.waiting = self.waiting + 1
Brett Cannon66865d22008-03-13 20:27:00 +0000168 if self.waiting == self.num_threads:
169 self.waiting = self.num_threads - 1
170 self.checkout_mutex.release()
Fred Drake004d5e62000-10-23 17:22:08 +0000171 return
Brett Cannon66865d22008-03-13 20:27:00 +0000172 self.checkin_mutex.release()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000173
Brett Cannon66865d22008-03-13 20:27:00 +0000174 self.checkout_mutex.acquire()
Fred Drake004d5e62000-10-23 17:22:08 +0000175 self.waiting = self.waiting - 1
176 if self.waiting == 0:
Brett Cannon66865d22008-03-13 20:27:00 +0000177 self.checkin_mutex.release()
Fred Drake004d5e62000-10-23 17:22:08 +0000178 return
Brett Cannon66865d22008-03-13 20:27:00 +0000179 self.checkout_mutex.release()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000180
Guido van Rossumd3b68421994-05-23 12:17:36 +0000181
Brett Cannon66865d22008-03-13 20:27:00 +0000182class BarrierTest(BasicThreadTest):
Andrew MacIntyre92913322006-06-13 15:04:24 +0000183
Brett Cannon66865d22008-03-13 20:27:00 +0000184 def test_barrier(self):
185 self.bar = Barrier(NUMTASKS)
186 self.running = NUMTASKS
187 for i in range(NUMTASKS):
188 thread.start_new_thread(self.task2, (i,))
189 verbose_print("waiting for tasks to end")
190 self.done_mutex.acquire()
191 verbose_print("tasks done")
Andrew MacIntyre92913322006-06-13 15:04:24 +0000192
Brett Cannon66865d22008-03-13 20:27:00 +0000193 def task2(self, ident):
194 for i in range(NUMTRIPS):
195 if ident == 0:
196 # give it a good chance to enter the next
197 # barrier before the others are all out
198 # of the current one
Jeffrey Yasskina1458532008-03-18 04:56:06 +0000199 delay = 0
Brett Cannon66865d22008-03-13 20:27:00 +0000200 else:
201 with self.random_mutex:
Jeffrey Yasskina1458532008-03-18 04:56:06 +0000202 delay = random.random() / 10000.0
203 verbose_print("task %s will run for %sus" %
204 (ident, round(delay * 1e6)))
Brett Cannon66865d22008-03-13 20:27:00 +0000205 time.sleep(delay)
206 verbose_print("task %s entering %s" % (ident, i))
207 self.bar.enter()
208 verbose_print("task %s leaving barrier" % ident)
209 with self.running_mutex:
210 self.running -= 1
211 # Must release mutex before releasing done, else the main thread can
212 # exit and set mutex to None as part of global teardown; then
213 # mutex.release() raises AttributeError.
214 finished = self.running == 0
215 if finished:
216 self.done_mutex.release()
Andrew MacIntyre92913322006-06-13 15:04:24 +0000217
Andrew MacIntyre92913322006-06-13 15:04:24 +0000218
Antoine Pitrouc98efe02009-11-06 22:34:35 +0000219class LockTests(lock_tests.LockTests):
220 locktype = thread.allocate_lock
221
222
Gregory P. Smith9e5d1322010-03-01 01:22:39 +0000223class TestForkInThread(unittest.TestCase):
224 def setUp(self):
225 self.read_fd, self.write_fd = os.pipe()
226
Gregory P. Smith7512a902010-03-01 06:01:02 +0000227 @unittest.skipIf(sys.platform.startswith('win'),
Florent Xicluna2e6d2622010-03-20 00:17:46 +0000228 "This test is only appropriate for POSIX-like systems.")
229 @test_support.reap_threads
Gregory P. Smith9e5d1322010-03-01 01:22:39 +0000230 def test_forkinthread(self):
Gregory P. Smith9e5d1322010-03-01 01:22:39 +0000231 def thread1():
232 try:
233 pid = os.fork() # fork in a thread
234 except RuntimeError:
235 sys.exit(0) # exit the child
236
237 if pid == 0: # child
238 os.close(self.read_fd)
239 os.write(self.write_fd, "OK")
Martin Panter20c8cd92016-03-08 07:07:28 +0000240 # Exiting the thread normally in the child process can leave
241 # any additional threads (such as the one started by
242 # importing _tkinter) still running, and this can prevent
243 # the half-zombie child process from being cleaned up. See
244 # Issue #26456.
245 os._exit(0)
Gregory P. Smith9e5d1322010-03-01 01:22:39 +0000246 else: # parent
247 os.close(self.write_fd)
Ammar Askar425680b2017-08-09 10:54:53 -0400248 pid, status = os.waitpid(pid, 0)
249 self.assertEqual(status, 0)
Gregory P. Smith9e5d1322010-03-01 01:22:39 +0000250
251 thread.start_new_thread(thread1, ())
252 self.assertEqual(os.read(self.read_fd, 2), "OK",
253 "Unable to fork() in thread")
254
255 def tearDown(self):
256 try:
257 os.close(self.read_fd)
258 except OSError:
259 pass
260
261 try:
262 os.close(self.write_fd)
263 except OSError:
264 pass
265
266
Brett Cannon66865d22008-03-13 20:27:00 +0000267def test_main():
Gregory P. Smith9e5d1322010-03-01 01:22:39 +0000268 test_support.run_unittest(ThreadRunningTests, BarrierTest, LockTests,
269 TestForkInThread)
Andrew MacIntyre92913322006-06-13 15:04:24 +0000270
Brett Cannon66865d22008-03-13 20:27:00 +0000271if __name__ == "__main__":
272 test_main()