blob: 2dd1593eaa0cb1399df46fc8ea3005d16729f75c [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
Victor Stinner45df8202010-04-28 22:31:17 +00005thread = support.import_module('_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):
62 # Basic test for thread creation.
63 for i in range(NUMTASKS):
64 self.newtask()
65 verbose_print("waiting for tasks to complete...")
66 self.done_mutex.acquire()
67 verbose_print("all tasks done")
68
69 def test_stack_size(self):
70 # Various stack size tests.
Florent Xicluna6709c0c2010-03-20 00:21:04 +000071 self.assertEqual(thread.stack_size(), 0, "initial stack size is not 0")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000072
73 thread.stack_size(0)
Florent Xicluna6709c0c2010-03-20 00:21:04 +000074 self.assertEqual(thread.stack_size(), 0, "stack_size not reset to default")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000075
Zachary Ware101d9e72013-12-08 00:44:27 -060076 @unittest.skipIf(os.name not in ("nt", "posix"), 'test meant for nt and posix')
Zachary Ware9fe6d862013-12-08 00:20:35 -060077 def test_nt_and_posix_stack_size(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +000078 try:
79 thread.stack_size(4096)
80 except ValueError:
81 verbose_print("caught expected ValueError setting "
82 "stack_size(4096)")
83 except thread.error:
Zachary Ware9fe6d862013-12-08 00:20:35 -060084 self.skipTest("platform does not support changing thread stack "
85 "size")
Christian Heimesdd15f6c2008-03-16 00:07:10 +000086
Zachary Ware9fe6d862013-12-08 00:20:35 -060087 fail_msg = "stack_size(%d) failed - should succeed"
88 for tss in (262144, 0x100000, 0):
89 thread.stack_size(tss)
90 self.assertEqual(thread.stack_size(), tss, fail_msg % tss)
91 verbose_print("successfully set stack_size(%d)" % tss)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000092
Zachary Ware9fe6d862013-12-08 00:20:35 -060093 for tss in (262144, 0x100000):
94 verbose_print("trying stack_size = (%d)" % tss)
95 self.next_ident = 0
96 self.created = 0
97 for i in range(NUMTASKS):
98 self.newtask()
Christian Heimesdd15f6c2008-03-16 00:07:10 +000099
Zachary Ware9fe6d862013-12-08 00:20:35 -0600100 verbose_print("waiting for all tasks to complete")
101 self.done_mutex.acquire()
102 verbose_print("all tasks done")
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000103
Zachary Ware9fe6d862013-12-08 00:20:35 -0600104 thread.stack_size(0)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000105
Antoine Pitrou65c9c642009-10-30 17:25:12 +0000106 def test__count(self):
107 # Test the _count() function.
108 orig = thread._count()
109 mut = thread.allocate_lock()
110 mut.acquire()
111 started = []
112 def task():
113 started.append(None)
114 mut.acquire()
115 mut.release()
116 thread.start_new_thread(task, ())
117 while not started:
Victor Stinnera15d1552017-09-12 10:49:22 -0700118 time.sleep(POLL_SLEEP)
Florent Xicluna6709c0c2010-03-20 00:21:04 +0000119 self.assertEqual(thread._count(), orig + 1)
Antoine Pitrou65c9c642009-10-30 17:25:12 +0000120 # Allow the task to finish.
121 mut.release()
122 # The only reliable way to be sure that the thread ended from the
123 # interpreter's point of view is to wait for the function object to be
124 # destroyed.
125 done = []
126 wr = weakref.ref(task, lambda _: done.append(None))
127 del task
128 while not done:
Victor Stinnera15d1552017-09-12 10:49:22 -0700129 time.sleep(POLL_SLEEP)
Florent Xicluna6709c0c2010-03-20 00:21:04 +0000130 self.assertEqual(thread._count(), orig)
Antoine Pitrou65c9c642009-10-30 17:25:12 +0000131
Benjamin Petersone9000962012-04-02 11:15:17 -0400132 def test_save_exception_state_on_error(self):
133 # See issue #14474
134 def task():
135 started.release()
Benjamin Petersone9000962012-04-02 11:15:17 -0400136 raise SyntaxError
137 def mywrite(self, *args):
138 try:
139 raise ValueError
140 except ValueError:
141 pass
142 real_write(self, *args)
143 c = thread._count()
144 started = thread.allocate_lock()
145 with support.captured_output("stderr") as stderr:
146 real_write = stderr.write
147 stderr.write = mywrite
148 started.acquire()
149 thread.start_new_thread(task, ())
150 started.acquire()
151 while thread._count() > c:
Victor Stinnera15d1552017-09-12 10:49:22 -0700152 time.sleep(POLL_SLEEP)
Benjamin Petersone9000962012-04-02 11:15:17 -0400153 self.assertIn("Traceback", stderr.getvalue())
154
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000155
156class Barrier:
157 def __init__(self, num_threads):
158 self.num_threads = num_threads
Fred Drake004d5e62000-10-23 17:22:08 +0000159 self.waiting = 0
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000160 self.checkin_mutex = thread.allocate_lock()
161 self.checkout_mutex = thread.allocate_lock()
162 self.checkout_mutex.acquire()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000163
Fred Drake004d5e62000-10-23 17:22:08 +0000164 def enter(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000165 self.checkin_mutex.acquire()
Fred Drake004d5e62000-10-23 17:22:08 +0000166 self.waiting = self.waiting + 1
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000167 if self.waiting == self.num_threads:
168 self.waiting = self.num_threads - 1
169 self.checkout_mutex.release()
Fred Drake004d5e62000-10-23 17:22:08 +0000170 return
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000171 self.checkin_mutex.release()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000172
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000173 self.checkout_mutex.acquire()
Fred Drake004d5e62000-10-23 17:22:08 +0000174 self.waiting = self.waiting - 1
175 if self.waiting == 0:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000176 self.checkin_mutex.release()
Fred Drake004d5e62000-10-23 17:22:08 +0000177 return
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000178 self.checkout_mutex.release()
Guido van Rossumd3b68421994-05-23 12:17:36 +0000179
Guido van Rossumd3b68421994-05-23 12:17:36 +0000180
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000181class BarrierTest(BasicThreadTest):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000182
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000183 def test_barrier(self):
184 self.bar = Barrier(NUMTASKS)
185 self.running = NUMTASKS
186 for i in range(NUMTASKS):
187 thread.start_new_thread(self.task2, (i,))
188 verbose_print("waiting for tasks to end")
189 self.done_mutex.acquire()
190 verbose_print("tasks done")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000192 def task2(self, ident):
193 for i in range(NUMTRIPS):
194 if ident == 0:
195 # give it a good chance to enter the next
196 # barrier before the others are all out
197 # of the current one
Christian Heimesb186d002008-03-18 15:15:01 +0000198 delay = 0
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000199 else:
200 with self.random_mutex:
Christian Heimesb186d002008-03-18 15:15:01 +0000201 delay = random.random() / 10000.0
202 verbose_print("task %s will run for %sus" %
203 (ident, round(delay * 1e6)))
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000204 time.sleep(delay)
205 verbose_print("task %s entering %s" % (ident, i))
206 self.bar.enter()
207 verbose_print("task %s leaving barrier" % ident)
208 with self.running_mutex:
209 self.running -= 1
210 # Must release mutex before releasing done, else the main thread can
211 # exit and set mutex to None as part of global teardown; then
212 # mutex.release() raises AttributeError.
213 finished = self.running == 0
214 if finished:
215 self.done_mutex.release()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000216
Antoine Pitrou557934f2009-11-06 22:41:14 +0000217class LockTests(lock_tests.LockTests):
218 locktype = thread.allocate_lock
219
220
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000221class TestForkInThread(unittest.TestCase):
222 def setUp(self):
223 self.read_fd, self.write_fd = os.pipe()
224
Victor Stinnera15d1552017-09-12 10:49:22 -0700225 @unittest.skipUnless(hasattr(os, 'fork'), 'need os.fork')
Florent Xicluna6709c0c2010-03-20 00:21:04 +0000226 @support.reap_threads
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000227 def test_forkinthread(self):
Victor Stinnera15d1552017-09-12 10:49:22 -0700228 running = True
229 status = "not set"
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000230
Victor Stinnera15d1552017-09-12 10:49:22 -0700231 def thread1():
232 nonlocal running, status
233
234 # fork in a thread
235 pid = os.fork()
236 if pid == 0:
237 # child
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000238 try:
239 os.close(self.read_fd)
240 os.write(self.write_fd, b"OK")
241 finally:
242 os._exit(0)
Victor Stinnera15d1552017-09-12 10:49:22 -0700243 else:
244 # parent
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000245 os.close(self.write_fd)
Ammar Askar88eee442017-08-09 04:51:43 -0400246 pid, status = os.waitpid(pid, 0)
Victor Stinnera15d1552017-09-12 10:49:22 -0700247 running = False
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000248
249 thread.start_new_thread(thread1, ())
250 self.assertEqual(os.read(self.read_fd, 2), b"OK",
251 "Unable to fork() in thread")
Victor Stinnera15d1552017-09-12 10:49:22 -0700252 while running:
253 time.sleep(POLL_SLEEP)
254 self.assertEqual(status, 0)
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000255
256 def tearDown(self):
257 try:
258 os.close(self.read_fd)
259 except OSError:
260 pass
261
262 try:
263 os.close(self.write_fd)
264 except OSError:
265 pass
266
267
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000268if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500269 unittest.main()