Exemplo n.º 1
0
 def main(n):
     try:
         from _thread import _local
     except ImportError:
         from thread import _local
     local = _local()
     local.x = 1
     i = 0
     while i < n:
         i += local.x
     return 0
Exemplo n.º 2
0
    def test_local_setdict(self):
        import _thread
        x = _thread._local()
        raises(AttributeError, "x.__dict__ = 42")
        raises(AttributeError, "x.__dict__ = {}")

        done = []
        def f(n):
            x.spam = n
            assert x.__dict__["spam"] == n
            done.append(1)
        for i in range(5):
            _thread.start_new_thread(f, (i,))
        self.waitfor(lambda: len(done) == 5, delay=2)
        assert len(done) == 5
Exemplo n.º 3
0
    def test_local_setdict(self):
        import _thread
        x = _thread._local()
        raises(AttributeError, "x.__dict__ = 42")
        raises(AttributeError, "x.__dict__ = {}")

        done = []

        def f(n):
            x.spam = n
            assert x.__dict__["spam"] == n
            done.append(1)

        for i in range(5):
            _thread.start_new_thread(f, (i, ))
        self.waitfor(lambda: len(done) == 5, delay=2)
        assert len(done) == 5
Exemplo n.º 4
0
def ffunc(q, *a):
    _thread.get_ident()
    _thread._count()
    _thread.stack_size()
    local = _thread._local()

    try:
        q.empty()
        q.qsize()
        ln = rnd.randint(0, 99)
        for _ in range(ln):
            rnd.choice([q.put, q.put_nowait])(fitem())
        for _ in range(ln):
            if fbool(): q.get(fbool(), rnd.random())
            else: q.get_nowait()
    except ReferenceError:
        pass

    return list(os.urandom(rnd.randint(0, 99)))
Exemplo n.º 5
0
    def test_thread_local(self):
        import _thread as thread
        from System.Threading import Thread
        x = thread._local()

        #--Sanity
        x.foo = 42
        self.assertEqual(x.foo, 42)

        global found
        found = None

        def f():
            global found
            found = hasattr(x, 'foo')

        thread.start_new_thread(f, ())

        while found == None:
            Thread.Sleep(100)

        self.assertTrue(not found)

        self.assertEqual(x.__dict__, {'foo': 42})
        try:
            x.__dict__ = None
            self.fail("Should not be able to set thread._local().__dict__!")
        except AttributeError as e:
            pass

        try:
            print(x.bar)
            self.fail("There is no 'bar' member on thread._local()")
        except AttributeError as e:
            pass

        del x.foo
        self.assertEqual(x.__dict__, {})
Exemplo n.º 6
0
def test_thread_local():
    import _thread
    x = _thread._local()

    #--Sanity
    x.foo = 42
    AreEqual(x.foo, 42)

    global found
    found = None

    def f():
        global found
        found = hasattr(x, 'foo')

    _thread.start_new_thread(f, ())

    while found == None:
        Thread.Sleep(100)

    Assert(not found)

    AreEqual(x.__dict__, {'foo': 42})
    try:
        x.__dict__ = None
        Fail("Should not be able to set thread._local().__dict__!")
    except AttributeError as e:
        pass

    try:
        print(x.bar)
        Fail("There is no 'bar' member on thread._local()")
    except AttributeError as e:
        pass

    del x.foo
    AreEqual(x.__dict__, {})
Exemplo n.º 7
0
    class Popen(object):
        '''
        Start a subprocess to run the code of a process object
        '''
        _tls = _thread._local()

        def __init__(self, process_obj):
            # create pipe for communication with child
            rfd, wfd = os.pipe()

            # get handle for read end of the pipe and make it inheritable
            rhandle = duplicate(msvcrt.get_osfhandle(rfd), inheritable=True)
            os.close(rfd)

            # start process
            cmd = get_command_line() + [rhandle]
            cmd = ' '.join('"%s"' % x for x in cmd)
            hp, ht, pid, tid = _subprocess.CreateProcess(
                _python_exe, cmd, None, None, 1, 0, None, None, None)
            ht.Close()
            close(rhandle)

            # set attributes of self
            self.pid = pid
            self.returncode = None
            self._handle = hp

            # send information to child
            prep_data = get_preparation_data(process_obj._name)
            to_child = os.fdopen(wfd, 'wb')
            Popen._tls.process_handle = int(hp)
            try:
                dump(prep_data, to_child, HIGHEST_PROTOCOL)
                dump(process_obj, to_child, HIGHEST_PROTOCOL)
            finally:
                del Popen._tls.process_handle
                to_child.close()

        @staticmethod
        def thread_is_spawning():
            return getattr(Popen._tls, 'process_handle', None) is not None

        @staticmethod
        def duplicate_for_child(handle):
            return duplicate(handle, Popen._tls.process_handle)

        def wait(self, timeout=None):
            if self.returncode is None:
                if timeout is None:
                    msecs = _subprocess.INFINITE
                else:
                    msecs = max(0, int(timeout * 1000 + 0.5))

                res = _subprocess.WaitForSingleObject(int(self._handle), msecs)
                if res == _subprocess.WAIT_OBJECT_0:
                    code = _subprocess.GetExitCodeProcess(self._handle)
                    if code == TERMINATE:
                        code = -signal.SIGTERM
                    self.returncode = code

            return self.returncode

        def poll(self):
            return self.wait(timeout=0)

        def terminate(self):
            if self.returncode is None:
                try:
                    _subprocess.TerminateProcess(int(self._handle), TERMINATE)
                except WindowsError:
                    if self.wait(timeout=0.1) is None:
                        raise
Exemplo n.º 8
0
 def test_weakrefable(self):
     import _thread, weakref
     weakref.ref(_thread._local())