blob: 64ffe460529816505ff6344baf9c83e7e858d489 [file] [log] [blame]
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001import os
2import unittest
Guido van Rossumb26a1b41998-05-20 17:05:52 +00003import random
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Antoine Pitrou88c60c92017-09-18 23:50:44 +02005import _thread as thread
Guido van Rossumcc544171994-04-14 20:28:41 +00006import time
Gregory P. Smith24cec9f2010-03-01 06:18:41 +00007import sys
Antoine Pitrou65c9c642009-10-30 17:25:12 +00008import weakref
Guido van Rossumcc544171994-04-14 20:28:41 +00009
Antoine Pitrou557934f2009-11-06 22:41:14 +000010from test import lock_tests
Guido van Rossumcc544171994-04-14 20:28:41 +000011
Christian Heimesdd15f6c2008-03-16 00:07:10 +000012NUMTASKS = 10
13NUMTRIPS = 3
Victor Stinnera15d1552017-09-12 10:49:22 -070014POLL_SLEEP = 0.010 # seconds = 10 ms
Guido van Rossumd3b68421994-05-23 12:17:36 +000015
Christian Heimesb186d002008-03-18 15:15:01 +000016_print_mutex = thread.allocate_lock()
17
Christian Heimesdd15f6c2008-03-16 00:07:10 +000018def verbose_print(arg):
19 """Helper function for printing out debugging output."""
Benjamin Petersonee8712c2008-05-20 21:35:26 +000020 if support.verbose:
Christian Heimesb186d002008-03-18 15:15:01 +000021 with _print_mutex:
22 print(arg)
Guido van Rossumcc544171994-04-14 20:28:41 +000023
Victor Stinner79ef7f82017-05-15 17:55:32 +020024
Christian Heimesdd15f6c2008-03-16 00:07:10 +000025class BasicThreadTest(unittest.TestCase):
Guido van Rossumcc544171994-04-14 20:28:41 +000026
Christian Heimesdd15f6c2008-03-16 00:07:10 +000027 def setUp(self):
28 self.done_mutex = thread.allocate_lock()
29 self.done_mutex.acquire()
30 self.running_mutex = thread.allocate_lock()
31 self.random_mutex = thread.allocate_lock()
Antoine Pitrou97115d12009-10-23 18:34:17 +000032 self.created = 0
Christian Heimesdd15f6c2008-03-16 00:07:10 +000033 self.running = 0
34 self.next_ident = 0
Guido van Rossumcc544171994-04-14 20:28:41 +000035
Victor Stinner79ef7f82017-05-15 17:55:32 +020036 key = support.threading_setup()
37 self.addCleanup(support.threading_cleanup, *key)
38
Guido van Rossumd3b68421994-05-23 12:17:36 +000039
Christian Heimesdd15f6c2008-03-16 00:07:10 +000040class ThreadRunningTests(BasicThreadTest):
41
42 def newtask(self):
43 with self.running_mutex:
44 self.next_ident += 1
45 verbose_print("creating task %s" % self.next_ident)
46 thread.start_new_thread(self.task, (self.next_ident,))
Antoine Pitrou97115d12009-10-23 18:34:17 +000047 self.created += 1
Christian Heimesdd15f6c2008-03-16 00:07:10 +000048 self.running += 1
49
50 def task(self, ident):
51 with self.random_mutex:
Christian Heimesb186d002008-03-18 15:15:01 +000052 delay = random.random() / 10000.0
53 verbose_print("task %s will run for %sus" % (ident, round(delay*1e6)))
Christian Heimesdd15f6c2008-03-16 00:07:10 +000054 time.sleep(delay)
55 verbose_print("task %s done" % ident)
56 with self.running_mutex:
57 self.running -= 1
Antoine Pitrou97115d12009-10-23 18:34:17 +000058 if self.created == NUMTASKS and self.running == 0:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000059 self.done_mutex.release()
60
61 def test_starting_threads(self):
Victor Stinnerff40ecd2017-09-14 13:07:24 -070062 with support.wait_threads_exit():
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")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000069
70 def test_stack_size(self):
71 # Various stack size tests.
Florent Xicluna6709c0c2010-03-20 00:21:04 +000072 self.assertEqual(thread.stack_size(), 0, "initial stack size is not 0")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000073
74 thread.stack_size(0)
Florent Xicluna6709c0c2010-03-20 00:21:04 +000075 self.assertEqual(thread.stack_size(), 0, "stack_size not reset to default")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000076
Zachary Ware101d9e72013-12-08 00:44:27 -060077 @unittest.skipIf(os.name not in ("nt", "posix"), 'test meant for nt and posix')
Zachary Ware9fe6d862013-12-08 00:20:35 -060078 def test_nt_and_posix_stack_size(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +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 Ware9fe6d862013-12-08 00:20:35 -060085 self.skipTest("platform does not support changing thread stack "
86 "size")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000087
Zachary Ware9fe6d862013-12-08 00:20:35 -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)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000093
Zachary Ware9fe6d862013-12-08 00:20:35 -060094 for tss in (262144, 0x100000):
95 verbose_print("trying stack_size = (%d)" % tss)
96 self.next_ident = 0
97 self.created = 0
Victor Stinnerff40ecd2017-09-14 13:07:24 -070098 with support.wait_threads_exit():
99 for i in range(NUMTASKS):
100 self.newtask()
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000101
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700102 verbose_print("waiting for all tasks to complete")
103 self.done_mutex.acquire()
104 verbose_print("all tasks done")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000105
Zachary Ware9fe6d862013-12-08 00:20:35 -0600106 thread.stack_size(0)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000107
Antoine Pitrou65c9c642009-10-30 17:25:12 +0000108 def test__count(self):
109 # Test the _count() function.
110 orig = thread._count()
111 mut = thread.allocate_lock()
112 mut.acquire()
113 started = []
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700114
Antoine Pitrou65c9c642009-10-30 17:25:12 +0000115 def task():
116 started.append(None)
117 mut.acquire()
118 mut.release()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700119
120 with support.wait_threads_exit():
121 thread.start_new_thread(task, ())
122 while not started:
123 time.sleep(POLL_SLEEP)
124 self.assertEqual(thread._count(), orig + 1)
125 # Allow the task to finish.
126 mut.release()
127 # The only reliable way to be sure that the thread ended from the
128 # interpreter's point of view is to wait for the function object to be
129 # destroyed.
130 done = []
131 wr = weakref.ref(task, lambda _: done.append(None))
132 del task
133 while not done:
134 time.sleep(POLL_SLEEP)
135 self.assertEqual(thread._count(), orig)
Antoine Pitrou65c9c642009-10-30 17:25:12 +0000136
Benjamin Petersone9000962012-04-02 11:15:17 -0400137 def test_save_exception_state_on_error(self):
138 # See issue #14474
139 def task():
140 started.release()
Benjamin Petersone9000962012-04-02 11:15:17 -0400141 raise SyntaxError
142 def mywrite(self, *args):
143 try:
144 raise ValueError
145 except ValueError:
146 pass
147 real_write(self, *args)
Benjamin Petersone9000962012-04-02 11:15:17 -0400148 started = thread.allocate_lock()
149 with support.captured_output("stderr") as stderr:
150 real_write = stderr.write
151 stderr.write = mywrite
152 started.acquire()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700153 with support.wait_threads_exit():
154 thread.start_new_thread(task, ())
155 started.acquire()
Benjamin Petersone9000962012-04-02 11:15:17 -0400156 self.assertIn("Traceback", stderr.getvalue())
157
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000158
159class Barrier:
160 def __init__(self, num_threads):
161 self.num_threads = num_threads
Fred Drake004d5e62000-10-23 17:22:08 +0000162 self.waiting = 0
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000163 self.checkin_mutex = thread.allocate_lock()
164 self.checkout_mutex = thread.allocate_lock()
165 self.checkout_mutex.acquire()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000166
Fred Drake004d5e62000-10-23 17:22:08 +0000167 def enter(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000168 self.checkin_mutex.acquire()
Fred Drake004d5e62000-10-23 17:22:08 +0000169 self.waiting = self.waiting + 1
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000170 if self.waiting == self.num_threads:
171 self.waiting = self.num_threads - 1
172 self.checkout_mutex.release()
Fred Drake004d5e62000-10-23 17:22:08 +0000173 return
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000174 self.checkin_mutex.release()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000175
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000176 self.checkout_mutex.acquire()
Fred Drake004d5e62000-10-23 17:22:08 +0000177 self.waiting = self.waiting - 1
178 if self.waiting == 0:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000179 self.checkin_mutex.release()
Fred Drake004d5e62000-10-23 17:22:08 +0000180 return
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000181 self.checkout_mutex.release()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000182
Guido van Rossumd3b68421994-05-23 12:17:36 +0000183
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000184class BarrierTest(BasicThreadTest):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000185
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000186 def test_barrier(self):
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700187 with support.wait_threads_exit():
188 self.bar = Barrier(NUMTASKS)
189 self.running = NUMTASKS
190 for i in range(NUMTASKS):
191 thread.start_new_thread(self.task2, (i,))
192 verbose_print("waiting for tasks to end")
193 self.done_mutex.acquire()
194 verbose_print("tasks done")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000195
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000196 def task2(self, ident):
197 for i in range(NUMTRIPS):
198 if ident == 0:
199 # give it a good chance to enter the next
200 # barrier before the others are all out
201 # of the current one
Christian Heimesb186d002008-03-18 15:15:01 +0000202 delay = 0
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000203 else:
204 with self.random_mutex:
Christian Heimesb186d002008-03-18 15:15:01 +0000205 delay = random.random() / 10000.0
206 verbose_print("task %s will run for %sus" %
207 (ident, round(delay * 1e6)))
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000208 time.sleep(delay)
209 verbose_print("task %s entering %s" % (ident, i))
210 self.bar.enter()
211 verbose_print("task %s leaving barrier" % ident)
212 with self.running_mutex:
213 self.running -= 1
214 # Must release mutex before releasing done, else the main thread can
215 # exit and set mutex to None as part of global teardown; then
216 # mutex.release() raises AttributeError.
217 finished = self.running == 0
218 if finished:
219 self.done_mutex.release()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000220
Antoine Pitrou557934f2009-11-06 22:41:14 +0000221class LockTests(lock_tests.LockTests):
222 locktype = thread.allocate_lock
223
224
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000225class TestForkInThread(unittest.TestCase):
226 def setUp(self):
227 self.read_fd, self.write_fd = os.pipe()
228
Victor Stinnera15d1552017-09-12 10:49:22 -0700229 @unittest.skipUnless(hasattr(os, 'fork'), 'need os.fork')
Florent Xicluna6709c0c2010-03-20 00:21:04 +0000230 @support.reap_threads
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000231 def test_forkinthread(self):
Victor Stinnera15d1552017-09-12 10:49:22 -0700232 status = "not set"
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000233
Victor Stinnera15d1552017-09-12 10:49:22 -0700234 def thread1():
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700235 nonlocal status
Victor Stinnera15d1552017-09-12 10:49:22 -0700236
237 # fork in a thread
238 pid = os.fork()
239 if pid == 0:
240 # child
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000241 try:
242 os.close(self.read_fd)
243 os.write(self.write_fd, b"OK")
244 finally:
245 os._exit(0)
Victor Stinnera15d1552017-09-12 10:49:22 -0700246 else:
247 # parent
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000248 os.close(self.write_fd)
Ammar Askar88eee442017-08-09 04:51:43 -0400249 pid, status = os.waitpid(pid, 0)
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000250
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700251 with support.wait_threads_exit():
252 thread.start_new_thread(thread1, ())
253 self.assertEqual(os.read(self.read_fd, 2), b"OK",
254 "Unable to fork() in thread")
Victor Stinnera15d1552017-09-12 10:49:22 -0700255 self.assertEqual(status, 0)
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000256
257 def tearDown(self):
258 try:
259 os.close(self.read_fd)
260 except OSError:
261 pass
262
263 try:
264 os.close(self.write_fd)
265 except OSError:
266 pass
267
268
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000269if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500270 unittest.main()