test_thread.py 7.44 KB
Newer Older
Christian Heimes's avatar
Christian Heimes committed
1 2
import os
import unittest
3
import random
4
from test import support
5
thread = support.import_module('_thread')
6
import time
7
import sys
8
import weakref
9

10
from test import lock_tests
Christian Heimes's avatar
Christian Heimes committed
11 12 13 14

NUMTASKS = 10
NUMTRIPS = 3

Christian Heimes's avatar
Christian Heimes committed
15 16
_print_mutex = thread.allocate_lock()

Christian Heimes's avatar
Christian Heimes committed
17 18
def verbose_print(arg):
    """Helper function for printing out debugging output."""
19
    if support.verbose:
Christian Heimes's avatar
Christian Heimes committed
20 21
        with _print_mutex:
            print(arg)
Christian Heimes's avatar
Christian Heimes committed
22 23 24 25 26 27 28 29

class BasicThreadTest(unittest.TestCase):

    def setUp(self):
        self.done_mutex = thread.allocate_lock()
        self.done_mutex.acquire()
        self.running_mutex = thread.allocate_lock()
        self.random_mutex = thread.allocate_lock()
30
        self.created = 0
Christian Heimes's avatar
Christian Heimes committed
31 32 33 34 35 36 37 38 39 40 41
        self.running = 0
        self.next_ident = 0


class ThreadRunningTests(BasicThreadTest):

    def newtask(self):
        with self.running_mutex:
            self.next_ident += 1
            verbose_print("creating task %s" % self.next_ident)
            thread.start_new_thread(self.task, (self.next_ident,))
42
            self.created += 1
Christian Heimes's avatar
Christian Heimes committed
43 44 45 46
            self.running += 1

    def task(self, ident):
        with self.random_mutex:
Christian Heimes's avatar
Christian Heimes committed
47 48
            delay = random.random() / 10000.0
        verbose_print("task %s will run for %sus" % (ident, round(delay*1e6)))
Christian Heimes's avatar
Christian Heimes committed
49 50 51 52
        time.sleep(delay)
        verbose_print("task %s done" % ident)
        with self.running_mutex:
            self.running -= 1
53
            if self.created == NUMTASKS and self.running == 0:
Christian Heimes's avatar
Christian Heimes committed
54 55 56 57 58 59 60 61 62 63 64 65
                self.done_mutex.release()

    def test_starting_threads(self):
        # Basic test for thread creation.
        for i in range(NUMTASKS):
            self.newtask()
        verbose_print("waiting for tasks to complete...")
        self.done_mutex.acquire()
        verbose_print("all tasks done")

    def test_stack_size(self):
        # Various stack size tests.
66
        self.assertEqual(thread.stack_size(), 0, "initial stack size is not 0")
Christian Heimes's avatar
Christian Heimes committed
67 68

        thread.stack_size(0)
69
        self.assertEqual(thread.stack_size(), 0, "stack_size not reset to default")
Christian Heimes's avatar
Christian Heimes committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

        if os.name not in ("nt", "os2", "posix"):
            return

        tss_supported = True
        try:
            thread.stack_size(4096)
        except ValueError:
            verbose_print("caught expected ValueError setting "
                            "stack_size(4096)")
        except thread.error:
            tss_supported = False
            verbose_print("platform does not support changing thread stack "
                            "size")

        if tss_supported:
            fail_msg = "stack_size(%d) failed - should succeed"
            for tss in (262144, 0x100000, 0):
                thread.stack_size(tss)
89
                self.assertEqual(thread.stack_size(), tss, fail_msg % tss)
Christian Heimes's avatar
Christian Heimes committed
90 91 92 93 94
                verbose_print("successfully set stack_size(%d)" % tss)

            for tss in (262144, 0x100000):
                verbose_print("trying stack_size = (%d)" % tss)
                self.next_ident = 0
95
                self.created = 0
Christian Heimes's avatar
Christian Heimes committed
96 97 98 99 100 101 102 103 104
                for i in range(NUMTASKS):
                    self.newtask()

                verbose_print("waiting for all tasks to complete")
                self.done_mutex.acquire()
                verbose_print("all tasks done")

            thread.stack_size(0)

105 106 107 108 109 110 111 112 113 114 115 116 117
    def test__count(self):
        # Test the _count() function.
        orig = thread._count()
        mut = thread.allocate_lock()
        mut.acquire()
        started = []
        def task():
            started.append(None)
            mut.acquire()
            mut.release()
        thread.start_new_thread(task, ())
        while not started:
            time.sleep(0.01)
118
        self.assertEqual(thread._count(), orig + 1)
119 120 121 122 123 124 125 126 127 128
        # Allow the task to finish.
        mut.release()
        # The only reliable way to be sure that the thread ended from the
        # interpreter's point of view is to wait for the function object to be
        # destroyed.
        done = []
        wr = weakref.ref(task, lambda _: done.append(None))
        del task
        while not done:
            time.sleep(0.01)
129
        self.assertEqual(thread._count(), orig)
130

Christian Heimes's avatar
Christian Heimes committed
131 132 133 134

class Barrier:
    def __init__(self, num_threads):
        self.num_threads = num_threads
135
        self.waiting = 0
Christian Heimes's avatar
Christian Heimes committed
136 137 138
        self.checkin_mutex  = thread.allocate_lock()
        self.checkout_mutex = thread.allocate_lock()
        self.checkout_mutex.acquire()
139

140
    def enter(self):
Christian Heimes's avatar
Christian Heimes committed
141
        self.checkin_mutex.acquire()
142
        self.waiting = self.waiting + 1
Christian Heimes's avatar
Christian Heimes committed
143 144 145
        if self.waiting == self.num_threads:
            self.waiting = self.num_threads - 1
            self.checkout_mutex.release()
146
            return
Christian Heimes's avatar
Christian Heimes committed
147
        self.checkin_mutex.release()
148

Christian Heimes's avatar
Christian Heimes committed
149
        self.checkout_mutex.acquire()
150 151
        self.waiting = self.waiting - 1
        if self.waiting == 0:
Christian Heimes's avatar
Christian Heimes committed
152
            self.checkin_mutex.release()
153
            return
Christian Heimes's avatar
Christian Heimes committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        self.checkout_mutex.release()


class BarrierTest(BasicThreadTest):

    def test_barrier(self):
        self.bar = Barrier(NUMTASKS)
        self.running = NUMTASKS
        for i in range(NUMTASKS):
            thread.start_new_thread(self.task2, (i,))
        verbose_print("waiting for tasks to end")
        self.done_mutex.acquire()
        verbose_print("tasks done")

    def task2(self, ident):
        for i in range(NUMTRIPS):
            if ident == 0:
                # give it a good chance to enter the next
                # barrier before the others are all out
                # of the current one
Christian Heimes's avatar
Christian Heimes committed
174
                delay = 0
Christian Heimes's avatar
Christian Heimes committed
175 176
            else:
                with self.random_mutex:
Christian Heimes's avatar
Christian Heimes committed
177 178 179
                    delay = random.random() / 10000.0
            verbose_print("task %s will run for %sus" %
                          (ident, round(delay * 1e6)))
Christian Heimes's avatar
Christian Heimes committed
180 181 182 183 184 185 186 187 188 189 190 191 192
            time.sleep(delay)
            verbose_print("task %s entering %s" % (ident, i))
            self.bar.enter()
            verbose_print("task %s leaving barrier" % ident)
        with self.running_mutex:
            self.running -= 1
            # Must release mutex before releasing done, else the main thread can
            # exit and set mutex to None as part of global teardown; then
            # mutex.release() raises AttributeError.
            finished = self.running == 0
        if finished:
            self.done_mutex.release()

193 194 195 196
class LockTests(lock_tests.LockTests):
    locktype = thread.allocate_lock


197 198 199 200 201
class TestForkInThread(unittest.TestCase):
    def setUp(self):
        self.read_fd, self.write_fd = os.pipe()

    @unittest.skipIf(sys.platform.startswith('win'),
202 203
                     "This test is only appropriate for POSIX-like systems.")
    @support.reap_threads
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    def test_forkinthread(self):
        def thread1():
            try:
                pid = os.fork() # fork in a thread
            except RuntimeError:
                os._exit(1) # exit the child

            if pid == 0: # child
                try:
                    os.close(self.read_fd)
                    os.write(self.write_fd, b"OK")
                finally:
                    os._exit(0)
            else: # parent
                os.close(self.write_fd)

        thread.start_new_thread(thread1, ())
        self.assertEqual(os.read(self.read_fd, 2), b"OK",
                         "Unable to fork() in thread")

    def tearDown(self):
        try:
            os.close(self.read_fd)
        except OSError:
            pass

        try:
            os.close(self.write_fd)
        except OSError:
            pass


Christian Heimes's avatar
Christian Heimes committed
236
def test_main():
237 238
    support.run_unittest(ThreadRunningTests, BarrierTest, LockTests,
                         TestForkInThread)
Christian Heimes's avatar
Christian Heimes committed
239 240 241

if __name__ == "__main__":
    test_main()