1ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh# Very rudimentary test of threading module
2ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
3ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport test.test_support
4ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehfrom test.test_support import verbose
5ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehfrom test.script_helper import assert_python_ok
6ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
7ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport random
8ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport re
9ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport sys
10ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehthread = test.test_support.import_module('thread')
11ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehthreading = test.test_support.import_module('threading')
12ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport time
13ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport unittest
14ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport weakref
15ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport os
16ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehimport subprocess
17ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
18ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehfrom test import lock_tests
19ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
20ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh# A trivial mutable counter.
21ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass Counter(object):
22ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def __init__(self):
23ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.value = 0
24ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def inc(self):
25ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.value += 1
26ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def dec(self):
27ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.value -= 1
28ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def get(self):
29ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        return self.value
30ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
31ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass TestThread(threading.Thread):
32ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def __init__(self, name, testcase, sema, mutex, nrunning):
33ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        threading.Thread.__init__(self, name=name)
34ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.testcase = testcase
35ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.sema = sema
36ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.mutex = mutex
37ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.nrunning = nrunning
38ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
39ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def run(self):
40ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        delay = random.random() / 10000.0
41ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
42ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print 'task %s will run for %.1f usec' % (
43ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.name, delay * 1e6)
44ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
45ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        with self.sema:
46ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            with self.mutex:
47ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.nrunning.inc()
48ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                if verbose:
49ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    print self.nrunning.get(), 'tasks are running'
50ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.testcase.assertTrue(self.nrunning.get() <= 3)
51ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
52ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            time.sleep(delay)
53ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            if verbose:
54ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                print 'task', self.name, 'done'
55ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
56ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            with self.mutex:
57ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.nrunning.dec()
58ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.testcase.assertTrue(self.nrunning.get() >= 0)
59ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                if verbose:
60ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    print '%s is finished. %d tasks are running' % (
61ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                        self.name, self.nrunning.get())
62ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
63ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass BaseTestCase(unittest.TestCase):
64ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def setUp(self):
65ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self._threads = test.test_support.threading_setup()
66ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
67ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def tearDown(self):
68ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        test.test_support.threading_cleanup(*self._threads)
69ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        test.test_support.reap_children()
70ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
71ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
72ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass ThreadTests(BaseTestCase):
73ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
74ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # Create a bunch of threads, let each do some work, wait until all are
75ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # done.
76ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_various_ops(self):
77ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # This takes about n/3 seconds to run (about n/3 clumps of tasks,
78ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # times about 1 second per clump).
79ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        NUMTASKS = 10
80ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
81ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # no more than 3 of the 10 can run at once
82ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        sema = threading.BoundedSemaphore(value=3)
83ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        mutex = threading.RLock()
84ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        numrunning = Counter()
85ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
86ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        threads = []
87ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
88ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        for i in range(NUMTASKS):
89ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
90ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            threads.append(t)
91ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertEqual(t.ident, None)
92ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
93ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.start()
94ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
95ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
96ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print 'waiting for all tasks to complete'
97ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        for t in threads:
98ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.join(NUMTASKS)
99ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertTrue(not t.is_alive())
100ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertNotEqual(t.ident, 0)
101ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertFalse(t.ident is None)
102ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
103ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
104ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print 'all tasks done'
105ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(numrunning.get(), 0)
106ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
107ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_ident_of_no_threading_threads(self):
108ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # The ident still must work for the main thread and dummy threads.
109ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertFalse(threading.currentThread().ident is None)
110ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        def f():
111ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            ident.append(threading.currentThread().ident)
112ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            done.set()
113ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        done = threading.Event()
114ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        ident = []
115ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        thread.start_new_thread(f, ())
116ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        done.wait()
117ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertFalse(ident[0] is None)
118ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Kill the "immortal" _DummyThread
119ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        del threading._active[ident[0]]
120ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
121ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # run with a small(ish) thread stack size (256kB)
122ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_various_ops_small_stack(self):
123ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
124ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print 'with 256kB thread stack size...'
125ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        try:
126ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            threading.stack_size(262144)
127ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        except thread.error:
128ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            if verbose:
129ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                print 'platform does not support changing thread stack size'
130ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            return
131ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.test_various_ops()
132ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        threading.stack_size(0)
133ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
134ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # run with a large thread stack size (1MB)
135ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_various_ops_large_stack(self):
136ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
137ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print 'with 1MB thread stack size...'
138ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        try:
139ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            threading.stack_size(0x100000)
140ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        except thread.error:
141ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            if verbose:
142ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                print 'platform does not support changing thread stack size'
143ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            return
144ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.test_various_ops()
145ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        threading.stack_size(0)
146ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
147ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_foreign_thread(self):
148ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Check that a "foreign" thread can use the threading module.
149ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        def f(mutex):
150ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # Calling current_thread() forces an entry for the foreign
151ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # thread to get made in the threading._active map.
152ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            threading.current_thread()
153ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            mutex.release()
154ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
155ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        mutex = threading.Lock()
156ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        mutex.acquire()
157ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        tid = thread.start_new_thread(f, (mutex,))
158ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Wait for the thread to finish.
159ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        mutex.acquire()
160ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertIn(tid, threading._active)
161ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertIsInstance(threading._active[tid], threading._DummyThread)
162ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        del threading._active[tid]
163ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
164ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
165ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # exposed at the Python level.  This test relies on ctypes to get at it.
166ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_PyThreadState_SetAsyncExc(self):
167ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        try:
168ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import ctypes
169ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        except ImportError:
170ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            if verbose:
171ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                print "test_PyThreadState_SetAsyncExc can't import ctypes"
172ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            return  # can't do anything
173ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
174ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
175ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
176ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        class AsyncExc(Exception):
177ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            pass
178ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
179ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        exception = ctypes.py_object(AsyncExc)
180ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
181ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # First check it works when setting the exception from the same thread.
182ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        tid = thread.get_ident()
183ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
184ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        try:
185ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            result = set_async_exc(ctypes.c_long(tid), exception)
186ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # The exception is async, so we might have to keep the VM busy until
187ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # it notices.
188ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            while True:
189ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                pass
190ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        except AsyncExc:
191ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            pass
192ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        else:
193ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # This code is unreachable but it reflects the intent. If we wanted
194ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # to be smarter the above loop wouldn't be infinite.
195ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.fail("AsyncExc not raised")
196ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        try:
197ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertEqual(result, 1) # one thread state modified
198ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        except UnboundLocalError:
199ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # The exception was raised too quickly for us to get the result.
200ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            pass
201ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
202ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # `worker_started` is set by the thread when it's inside a try/except
203ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # block waiting to catch the asynchronously set AsyncExc exception.
204ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # `worker_saw_exception` is set by the thread upon catching that
205ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # exception.
206ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        worker_started = threading.Event()
207ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        worker_saw_exception = threading.Event()
208ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
209ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        class Worker(threading.Thread):
210ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def run(self):
211ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.id = thread.get_ident()
212ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.finished = False
213ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
214ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                try:
215ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    while True:
216ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                        worker_started.set()
217ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                        time.sleep(0.1)
218ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                except AsyncExc:
219ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    self.finished = True
220ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    worker_saw_exception.set()
221ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
222ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        t = Worker()
223ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        t.daemon = True # so if this fails, we don't hang Python at shutdown
224ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        t.start()
225ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
226ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print "    started worker thread"
227ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
228ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Try a thread id that doesn't make sense.
229ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
230ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print "    trying nonsensical thread id"
231ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        result = set_async_exc(ctypes.c_long(-1), exception)
232ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(result, 0)  # no thread states modified
233ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
234ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Now raise an exception in the worker thread.
235ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
236ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print "    waiting for worker thread to get started"
237ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        ret = worker_started.wait()
238ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertTrue(ret)
239ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
240ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print "    verifying worker hasn't exited"
241ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertTrue(not t.finished)
242ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
243ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print "    attempting to raise asynch exception in worker"
244ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        result = set_async_exc(ctypes.c_long(t.id), exception)
245ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(result, 1) # one thread state modified
246ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
247ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print "    waiting for worker to say it caught the exception"
248ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        worker_saw_exception.wait(timeout=10)
249ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertTrue(t.finished)
250ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if verbose:
251ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print "    all OK -- joining worker"
252ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        if t.finished:
253ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.join()
254ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # else the thread is still running, and we have no way to kill it
255ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
256ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_limbo_cleanup(self):
257ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Issue 7481: Failure to start thread should cleanup the limbo map.
258ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        def fail_new_thread(*args):
259ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            raise thread.error()
260ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        _start_new_thread = threading._start_new_thread
261ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        threading._start_new_thread = fail_new_thread
262ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        try:
263ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t = threading.Thread(target=lambda: None)
264ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertRaises(thread.error, t.start)
265ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            self.assertFalse(
266ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                t in threading._limbo,
267ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                "Failed to cleanup _limbo map on failure of Thread.start().")
268ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        finally:
269ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            threading._start_new_thread = _start_new_thread
270ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
271ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_finalize_runnning_thread(self):
272ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Issue 1402: the PyGILState_Ensure / _Release functions may be called
273ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # very late on python exit: on deallocation of a running thread for
274ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # example.
275ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        try:
276ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import ctypes
277ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        except ImportError:
278ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            if verbose:
279ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                print("test_finalize_with_runnning_thread can't import ctypes")
280ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            return  # can't do anything
281ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
282ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        rc = subprocess.call([sys.executable, "-c", """if 1:
283ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import ctypes, sys, time, thread
284ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
285ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # This lock is used as a simple event variable.
286ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            ready = thread.allocate_lock()
287ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            ready.acquire()
288ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
289ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # Module globals are cleared before __del__ is run
290ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # So we save the functions in class dict
291ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            class C:
292ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                ensure = ctypes.pythonapi.PyGILState_Ensure
293ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                release = ctypes.pythonapi.PyGILState_Release
294ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                def __del__(self):
295ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    state = self.ensure()
296ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    self.release(state)
297ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
298ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def waitingThread():
299ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                x = C()
300ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                ready.release()
301ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                time.sleep(100)
302ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
303ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            thread.start_new_thread(waitingThread, ())
304ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            ready.acquire()  # Be sure the other thread is waiting.
305ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            sys.exit(42)
306ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """])
307ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(rc, 42)
308ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
309ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_finalize_with_trace(self):
310ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Issue1733757
311ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Avoid a deadlock when sys.settrace steps into threading._shutdown
312ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        p = subprocess.Popen([sys.executable, "-c", """if 1:
313ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import sys, threading
314ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
315ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # A deadlock-killer, to prevent the
316ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # testsuite to hang forever
317ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def killer():
318ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                import os, time
319ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                time.sleep(2)
320ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                print 'program blocked; aborting'
321ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                os._exit(2)
322ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t = threading.Thread(target=killer)
323ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.daemon = True
324ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.start()
325ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
326ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # This is the trace function
327ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def func(frame, event, arg):
328ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                threading.current_thread()
329ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                return func
330ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
331ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            sys.settrace(func)
332ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """],
333ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            stdout=subprocess.PIPE,
334ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            stderr=subprocess.PIPE)
335ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.addCleanup(p.stdout.close)
336ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.addCleanup(p.stderr.close)
337ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        stdout, stderr = p.communicate()
338ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        rc = p.returncode
339ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertFalse(rc == 2, "interpreted was blocked")
340ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertTrue(rc == 0,
341ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                        "Unexpected error: " + repr(stderr))
342ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
343ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_join_nondaemon_on_shutdown(self):
344ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Issue 1722344
345ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Raising SystemExit skipped threading._shutdown
346ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        p = subprocess.Popen([sys.executable, "-c", """if 1:
347ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                import threading
348ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                from time import sleep
349ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
350ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                def child():
351ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    sleep(1)
352ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    # As a non-daemon thread we SHOULD wake up and nothing
353ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    # should be torn down yet
354ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    print "Woke up, sleep function is:", sleep
355ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
356ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                threading.Thread(target=child).start()
357ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                raise SystemExit
358ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """],
359ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            stdout=subprocess.PIPE,
360ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            stderr=subprocess.PIPE)
361ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.addCleanup(p.stdout.close)
362ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.addCleanup(p.stderr.close)
363ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        stdout, stderr = p.communicate()
364ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(stdout.strip(),
365ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            "Woke up, sleep function is: <built-in function sleep>")
366ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip()
367ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(stderr, "")
368ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
369ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_enumerate_after_join(self):
370ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Try hard to trigger #1703448: a thread is still returned in
371ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # threading.enumerate() after it has been join()ed.
372ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        enum = threading.enumerate
373ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        old_interval = sys.getcheckinterval()
374ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        try:
375ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            for i in xrange(1, 100):
376ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # Try a couple times at each thread-switching interval
377ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # to get more interleavings.
378ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                sys.setcheckinterval(i // 5)
379ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                t = threading.Thread(target=lambda: None)
380ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                t.start()
381ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                t.join()
382ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                l = enum()
383ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.assertNotIn(t, l,
384ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    "#1703448 triggered after %d trials: %s" % (i, l))
385ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        finally:
386ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            sys.setcheckinterval(old_interval)
387ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
388ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_no_refcycle_through_target(self):
389ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        class RunSelfFunction(object):
390ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def __init__(self, should_raise):
391ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # The links in this refcycle from Thread back to self
392ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # should be cleaned up when the thread completes.
393ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.should_raise = should_raise
394ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.thread = threading.Thread(target=self._run,
395ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                               args=(self,),
396ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                               kwargs={'yet_another':self})
397ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                self.thread.start()
398ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
399ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def _run(self, other_ref, yet_another):
400ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                if self.should_raise:
401ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    raise SystemExit
402ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
403ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        cyclic_object = RunSelfFunction(should_raise=False)
404ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        weak_cyclic_object = weakref.ref(cyclic_object)
405ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        cyclic_object.thread.join()
406ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        del cyclic_object
407ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(None, weak_cyclic_object(),
408ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                         msg=('%d references still around' %
409ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                              sys.getrefcount(weak_cyclic_object())))
410ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
411ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        raising_cyclic_object = RunSelfFunction(should_raise=True)
412ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
413ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        raising_cyclic_object.thread.join()
414ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        del raising_cyclic_object
415ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(None, weak_raising_cyclic_object(),
416ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                         msg=('%d references still around' %
417ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                              sys.getrefcount(weak_raising_cyclic_object())))
418ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
419ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
420ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_dummy_thread_after_fork(self):
421ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Issue #14308: a dummy thread in the active list doesn't mess up
422ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # the after-fork mechanism.
423ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        code = """if 1:
424ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import thread, threading, os, time
425ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
426ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def background_thread(evt):
427ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # Creates and registers the _DummyThread instance
428ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                threading.current_thread()
429ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                evt.set()
430ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                time.sleep(10)
431ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
432ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            evt = threading.Event()
433ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            thread.start_new_thread(background_thread, (evt,))
434ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            evt.wait()
435ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            assert threading.active_count() == 2, threading.active_count()
436ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            if os.fork() == 0:
437ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                assert threading.active_count() == 1, threading.active_count()
438ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                os._exit(0)
439ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            else:
440ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                os.wait()
441ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        """
442ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        _, out, err = assert_python_ok("-c", code)
443ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(out, '')
444ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(err, '')
445ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
446ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
447ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass ThreadJoinOnShutdown(BaseTestCase):
448ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
449ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # Between fork() and exec(), only async-safe functions are allowed (issues
450ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # #12316 and #11870), and fork() from a worker thread is known to trigger
451ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # problems with some operating systems (issue #3863): skip problematic tests
452ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # on platforms known to behave badly.
453ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
454ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                         'os2emx')
455ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
456ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def _run_and_join(self, script):
457ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        script = """if 1:
458ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import sys, os, time, threading
459ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
460ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # a thread, which waits for the main program to terminate
461ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def joiningfunc(mainthread):
462ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                mainthread.join()
463ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                print 'end of thread'
464ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        \n""" + script
465ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
466ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
467ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        rc = p.wait()
468ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        data = p.stdout.read().replace('\r', '')
469ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        p.stdout.close()
470ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(data, "end of main\nend of thread\n")
471ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertFalse(rc == 2, "interpreter was blocked")
472ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertTrue(rc == 0, "Unexpected error")
473ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
474ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_1_join_on_shutdown(self):
475ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # The usual case: on exit, wait for a non-daemon thread
476ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        script = """if 1:
477ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import os
478ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t = threading.Thread(target=joiningfunc,
479ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                 args=(threading.current_thread(),))
480ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.start()
481ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            time.sleep(0.1)
482ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print 'end of main'
483ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """
484ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self._run_and_join(script)
485ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
486ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
487ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
488ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
489ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_2_join_in_forked_process(self):
490ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Like the test above, but from a forked interpreter
491ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        script = """if 1:
492ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            childpid = os.fork()
493ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            if childpid != 0:
494ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                os.waitpid(childpid, 0)
495ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                sys.exit(0)
496ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
497ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t = threading.Thread(target=joiningfunc,
498ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                 args=(threading.current_thread(),))
499ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.start()
500ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print 'end of main'
501ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """
502ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self._run_and_join(script)
503ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
504ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
505ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
506ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_3_join_in_forked_from_thread(self):
507ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Like the test above, but fork() was called from a worker thread
508ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # In the forked process, the main Thread object must be marked as stopped.
509ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        script = """if 1:
510ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            main_thread = threading.current_thread()
511ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def worker():
512ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                childpid = os.fork()
513ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                if childpid != 0:
514ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    os.waitpid(childpid, 0)
515ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    sys.exit(0)
516ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
517ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                t = threading.Thread(target=joiningfunc,
518ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                     args=(main_thread,))
519ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                print 'end of main'
520ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                t.start()
521ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                t.join() # Should not block: main_thread is already stopped
522ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
523ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w = threading.Thread(target=worker)
524ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w.start()
525ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """
526ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self._run_and_join(script)
527ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
528ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def assertScriptHasOutput(self, script, expected_output):
529ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        p = subprocess.Popen([sys.executable, "-c", script],
530ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                             stdout=subprocess.PIPE)
531ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        rc = p.wait()
532ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        data = p.stdout.read().decode().replace('\r', '')
533ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(rc, 0, "Unexpected error")
534ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(data, expected_output)
535ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
536ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
537ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
538ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_4_joining_across_fork_in_worker_thread(self):
539ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # There used to be a possible deadlock when forking from a child
540ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # thread.  See http://bugs.python.org/issue6643.
541ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
542ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # The script takes the following steps:
543ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # - The main thread in the parent process starts a new thread and then
544ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   tries to join it.
545ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # - The join operation acquires the Lock inside the thread's _block
546ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   Condition.  (See threading.py:Thread.join().)
547ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # - We stub out the acquire method on the condition to force it to wait
548ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   until the child thread forks.  (See LOCK ACQUIRED HERE)
549ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # - The child thread forks.  (See LOCK HELD and WORKER THREAD FORKS
550ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   HERE)
551ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # - The main thread of the parent process enters Condition.wait(),
552ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   which releases the lock on the child thread.
553ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # - The child process returns.  Without the necessary fix, when the
554ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   main thread of the child process (which used to be the child thread
555ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   in the parent process) attempts to exit, it will try to acquire the
556ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   lock in the Thread._block Condition object and hang, because the
557ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        #   lock was held across the fork.
558ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
559ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        script = """if 1:
560ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import os, time, threading
561ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
562ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            finish_join = False
563ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            start_fork = False
564ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
565ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def worker():
566ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # Wait until this thread's lock is acquired before forking to
567ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # create the deadlock.
568ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                global finish_join
569ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                while not start_fork:
570ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    time.sleep(0.01)
571ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # LOCK HELD: Main thread holds lock across this call.
572ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                childpid = os.fork()
573ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                finish_join = True
574ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                if childpid != 0:
575ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    # Parent process just waits for child.
576ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    os.waitpid(childpid, 0)
577ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # Child process should just return.
578ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
579ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w = threading.Thread(target=worker)
580ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
581ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # Stub out the private condition variable's lock acquire method.
582ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # This acquires the lock and then waits until the child has forked
583ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # before returning, which will release the lock soon after.  If
584ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # someone else tries to fix this test case by acquiring this lock
585ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # before forking instead of resetting it, the test case will
586ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # deadlock when it shouldn't.
587ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            condition = w._block
588ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            orig_acquire = condition.acquire
589ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            call_count_lock = threading.Lock()
590ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            call_count = 0
591ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def my_acquire():
592ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                global call_count
593ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                global start_fork
594ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                orig_acquire()  # LOCK ACQUIRED HERE
595ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                start_fork = True
596ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                if call_count == 0:
597ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    while not finish_join:
598ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                        time.sleep(0.01)  # WORKER THREAD FORKS HERE
599ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                with call_count_lock:
600ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    call_count += 1
601ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            condition.acquire = my_acquire
602ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
603ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w.start()
604ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w.join()
605ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print('end of main')
606ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """
607ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertScriptHasOutput(script, "end of main\n")
608ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
609ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
610ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
611ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_5_clear_waiter_locks_to_avoid_crash(self):
612ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Check that a spawned thread that forks doesn't segfault on certain
613ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # platforms, namely OS X.  This used to happen if there was a waiter
614ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # lock in the thread's condition variable's waiters list.  Even though
615ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # we know the lock will be held across the fork, it is not safe to
616ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # release locks held across forks on all platforms, so releasing the
617ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # waiter lock caused a segfault on OS X.  Furthermore, since locks on
618ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # OS X are (as of this writing) implemented with a mutex + condition
619ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # variable instead of a semaphore, while we know that the Python-level
620ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # lock will be acquired, we can't know if the internal mutex will be
621ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # acquired at the time of the fork.
622ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
623ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        script = """if True:
624ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import os, time, threading
625ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
626ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            start_fork = False
627ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
628ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def worker():
629ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # Wait until the main thread has attempted to join this thread
630ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # before continuing.
631ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                while not start_fork:
632ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    time.sleep(0.01)
633ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                childpid = os.fork()
634ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                if childpid != 0:
635ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    # Parent process just waits for child.
636ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    (cpid, rc) = os.waitpid(childpid, 0)
637ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    assert cpid == childpid
638ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    assert rc == 0
639ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    print('end of worker thread')
640ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                else:
641ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    # Child process should just return.
642ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    pass
643ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
644ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w = threading.Thread(target=worker)
645ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
646ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # Stub out the private condition variable's _release_save method.
647ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # This releases the condition's lock and flips the global that
648ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # causes the worker to fork.  At this point, the problematic waiter
649ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # lock has been acquired once by the waiter and has been put onto
650ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # the waiters list.
651ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            condition = w._block
652ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            orig_release_save = condition._release_save
653ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def my_release_save():
654ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                global start_fork
655ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                orig_release_save()
656ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                # Waiter lock held here, condition lock released.
657ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                start_fork = True
658ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            condition._release_save = my_release_save
659ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
660ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w.start()
661ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w.join()
662ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print('end of main thread')
663ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """
664ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        output = "end of worker thread\nend of main thread\n"
665ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertScriptHasOutput(script, output)
666ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
667ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
668ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
669ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_reinit_tls_after_fork(self):
670ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Issue #13817: fork() would deadlock in a multithreaded program with
671ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # the ad-hoc TLS implementation.
672ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
673ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        def do_fork_and_wait():
674ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            # just fork a child process and wait it
675ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            pid = os.fork()
676ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            if pid > 0:
677ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                os.waitpid(pid, 0)
678ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            else:
679ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                os._exit(0)
680ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
681ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # start a bunch of threads that will fork() child processes
682ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        threads = []
683ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        for i in range(16):
684ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t = threading.Thread(target=do_fork_and_wait)
685ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            threads.append(t)
686ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.start()
687ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
688ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        for t in threads:
689ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            t.join()
690ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
691ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
692ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass ThreadingExceptionTests(BaseTestCase):
693ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # A RuntimeError should be raised if Thread.start() is called
694ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # multiple times.
695ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_start_thread_again(self):
696ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        thread = threading.Thread()
697ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        thread.start()
698ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertRaises(RuntimeError, thread.start)
699ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
700ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_joining_current_thread(self):
701ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        current_thread = threading.current_thread()
702ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertRaises(RuntimeError, current_thread.join);
703ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
704ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_joining_inactive_thread(self):
705ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        thread = threading.Thread()
706ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertRaises(RuntimeError, thread.join)
707ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
708ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_daemonize_active_thread(self):
709ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        thread = threading.Thread()
710ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        thread.start()
711ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
712ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
713ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
714ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass LockTests(lock_tests.LockTests):
715ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    locktype = staticmethod(threading.Lock)
716ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
717ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass RLockTests(lock_tests.RLockTests):
718ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    locktype = staticmethod(threading.RLock)
719ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
720ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass EventTests(lock_tests.EventTests):
721ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    eventtype = staticmethod(threading.Event)
722ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
723ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass ConditionAsRLockTests(lock_tests.RLockTests):
724ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    # An Condition uses an RLock by default and exports its API.
725ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    locktype = staticmethod(threading.Condition)
726ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
727ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass ConditionTests(lock_tests.ConditionTests):
728ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    condtype = staticmethod(threading.Condition)
729ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
730ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass SemaphoreTests(lock_tests.SemaphoreTests):
731ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    semtype = staticmethod(threading.Semaphore)
732ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
733ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehclass BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
734ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    semtype = staticmethod(threading.BoundedSemaphore)
735ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
736ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem')
737ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    def test_recursion_limit(self):
738ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # Issue 9670
739ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # test that excessive recursion within a non-main thread causes
740ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # an exception rather than crashing the interpreter on platforms
741ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # like Mac OS X or FreeBSD which have small default stack sizes
742ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        # for threads
743ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        script = """if True:
744ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            import threading
745ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
746ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def recurse():
747ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                return recurse()
748ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
749ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            def outer():
750ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                try:
751ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    recurse()
752ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                except RuntimeError:
753ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                    pass
754ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
755ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w = threading.Thread(target=outer)
756ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w.start()
757ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            w.join()
758ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            print('end of main thread')
759ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh            """
760ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        expected_output = "end of main thread\n"
761ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        p = subprocess.Popen([sys.executable, "-c", script],
762ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                             stdout=subprocess.PIPE)
763ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        stdout, stderr = p.communicate()
764ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        data = stdout.decode().replace('\r', '')
765ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(p.returncode, 0, "Unexpected error")
766ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh        self.assertEqual(data, expected_output)
767ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
768ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehdef test_main():
769ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    test.test_support.run_unittest(LockTests, RLockTests, EventTests,
770ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                   ConditionAsRLockTests, ConditionTests,
771ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                   SemaphoreTests, BoundedSemaphoreTests,
772ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                   ThreadTests,
773ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                   ThreadJoinOnShutdown,
774ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                   ThreadingExceptionTests,
775ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh                                   )
776ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh
777ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsiehif __name__ == "__main__":
778ffab958fd8d42ed7227d83007350e61555a1fa36Andrew Hsieh    test_main()
779