[3.6] bpo-31234: Enhance test_thread.test_forkinthread() (GH-3516) (#… · python/cpython@bcf042f
@@ -11,6 +11,7 @@
11111212NUMTASKS = 10
1313NUMTRIPS = 3
14+POLL_SLEEP = 0.010 # seconds = 10 ms
14151516_print_mutex = thread.allocate_lock()
1617@@ -114,7 +115,7 @@ def task():
114115mut.release()
115116thread.start_new_thread(task, ())
116117while not started:
117-time.sleep(0.01)
118+time.sleep(POLL_SLEEP)
118119self.assertEqual(thread._count(), orig + 1)
119120# Allow the task to finish.
120121mut.release()
@@ -125,7 +126,7 @@ def task():
125126wr = weakref.ref(task, lambda _: done.append(None))
126127del task
127128while not done:
128-time.sleep(0.01)
129+time.sleep(POLL_SLEEP)
129130self.assertEqual(thread._count(), orig)
130131131132def test_save_exception_state_on_error(self):
@@ -148,7 +149,7 @@ def mywrite(self, *args):
148149thread.start_new_thread(task, ())
149150started.acquire()
150151while thread._count() > c:
151-time.sleep(0.01)
152+time.sleep(POLL_SLEEP)
152153self.assertIn("Traceback", stderr.getvalue())
153154154155@@ -221,30 +222,36 @@ class TestForkInThread(unittest.TestCase):
221222def setUp(self):
222223self.read_fd, self.write_fd = os.pipe()
223224224-@unittest.skipIf(sys.platform.startswith('win'),
225- "This test is only appropriate for POSIX-like systems.")
225+@unittest.skipUnless(hasattr(os, 'fork'), 'need os.fork')
226226@support.reap_threads
227227def test_forkinthread(self):
228+running = True
229+status = "not set"
230+228231def thread1():
229-try:
230-pid = os.fork() # fork in a thread
231-except RuntimeError:
232-os._exit(1) # exit the child
232+nonlocal running, status
233233234-if pid == 0: # child
234+# fork in a thread
235+pid = os.fork()
236+if pid == 0:
237+# child
235238try:
236239os.close(self.read_fd)
237240os.write(self.write_fd, b"OK")
238241finally:
239242os._exit(0)
240-else: # parent
243+else:
244+# parent
241245os.close(self.write_fd)
242246pid, status = os.waitpid(pid, 0)
243-self.assertEqual(status, 0)
247+running = False
244248245249thread.start_new_thread(thread1, ())
246250self.assertEqual(os.read(self.read_fd, 2), b"OK",
247251"Unable to fork() in thread")
252+while running:
253+time.sleep(POLL_SLEEP)
254+self.assertEqual(status, 0)
248255249256def tearDown(self):
250257try: