Пример #1
0
    def test_thread_local(self):
        import 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, e:
            pass
Пример #2
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(1000)

    Assert(not found)
    
    AreEqual(x.__dict__, {'foo': 42})
    try:
        x.__dict__ = None
        Fail("Should not be able to set thread._local().__dict__!")
    except AttributeError, e:
        pass
Пример #3
0
 def main(n):
     import thread
     local = thread._local()
     local.x = 1
     i = 0
     while i < n:
         i += local.x
     return 0
Пример #4
0
def f():
    global r
    l = thread._local()
    class C(object):
        pass
    o = C()
    r = _weakref.ref(o)
    l.o = o
    del o
    print type(r())
    del l
Пример #5
0
    def __init__(self, FIELDTYPE, fieldname, loop_invariant=False):
        "NOT_RPYTHON: must be prebuilt"
        try:
            from thread import _local
        except ImportError:
            class _local(object):
                pass
        self.FIELDTYPE = FIELDTYPE
        self.fieldname = fieldname
        self.local = _local()      # <- NOT_RPYTHON
        zero = rffi.cast(FIELDTYPE, 0)
        offset = CDefinedIntSymbolic('RPY_TLOFS_%s' % self.fieldname,
                                     default='?')
        offset.loop_invariant = loop_invariant
        self.offset = offset

        def getraw():
            if we_are_translated():
                _threadlocalref_seeme(self)
                return llop.threadlocalref_get(FIELDTYPE, offset)
            else:
                return getattr(self.local, 'rawvalue', zero)

        @jit.dont_look_inside
        def get_or_make_raw():
            if we_are_translated():
                _threadlocalref_seeme(self)
                addr = llop.threadlocalref_addr(llmemory.Address)
                return llop.raw_load(FIELDTYPE, addr, offset)
            else:
                return getattr(self.local, 'rawvalue', zero)

        @jit.dont_look_inside
        def setraw(value):
            if we_are_translated():
                _threadlocalref_seeme(self)
                addr = llop.threadlocalref_addr(llmemory.Address)
                llop.raw_store(lltype.Void, addr, offset, value)
            else:
                self.local.rawvalue = value

        def getoffset():
            _threadlocalref_seeme(self)
            return offset

        self.getraw = getraw
        self.get_or_make_raw = get_or_make_raw
        self.setraw = setraw
        self.getoffset = getoffset
Пример #6
0
 def test_local_setdict(self):
     import thread
     x = thread._local()
     raises(TypeError, "x.__dict__ = 42")
     done = []
     def f(n):
         x.spam = n
         assert x.__dict__["spam"] == n
         x.__dict__ = {"bar": n+1}
         assert x.bar == n+1
         assert not hasattr(x, "spam")
         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
Пример #7
0
    def test_local_setdict(self):
        import thread
        x = thread._local()
        # XXX: On Cpython these are AttributeErrors
        raises(TypeError, "x.__dict__ = 42")
        raises(TypeError, "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
Пример #8
0
        def codepred(obj):
            return False
    def bltpred(obj, modname = module.__name__):
        return obj.__module__ and obj.__module__.startswith(modname)
    
    for func in _get_all_functions(codepred, bltpred):
        ignore_function(func, mode)

#===============================================================================
# threading
#===============================================================================
_rotdirs = {}
_thread_counter = itertools.count()
_orig_start_new_thread = thread.start_new_thread
_orig_start_new = thread.start_new
_per_thread = thread._local()

def _thread_wrapper(func, args, kwargs):
    with _traced(_per_thread.rotdir, template = _per_thread.template, 
            map_size = _per_thread.map_size, file_size = _per_thread.file_size):
        return func(*args, **kwargs)

def _start_new_thread(func, args, kwargs = {}):
    if _per_thread.traced and _per_thread.trace_children:
        return _orig_start_new_thread(_thread_wrapper, (func, args, kwargs))
    else:
        return _orig_start_new_thread(func, args, kwargs)

thread.start_new_thread = thread.start_new = _start_new_thread

@contextmanager
Пример #9
0
# Windows
#

else:
    import imp, thread, msvcrt, _subprocess
    from os.path import dirname, splitext, basename, abspath
    from cPickle import dump, load, HIGHEST_PROTOCOL
    from processing._processing import win32
    from processing._processing import _hInterruptEvent, _main_thread_ident
    from processing.finalize import Finalize

    TERMINATE = 0x10000
    WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False))

    exit = win32.ExitProcess
    tls = thread._local()

    def thisThreadIsSpawning():
        return getattr(tls, 'is_spawning', False)

    #
    # We define a Popen class similar to the one from subprocess, but
    # whose constructor takes a process object as its argument, and which
    # has terminate() and waitTimeout() methods.
    #

    class Popen(object):
        '''
        Start a subprocess to run the code of a process object
        '''
        def __init__(self, process_obj):
Пример #10
0
#!/opt/Apps/local/Python/anaconda/bin/python2.7
__author__ = 'jiayun.wei'

import thread
import random
import time
import sys

response = thread._local()

response.abc = 1

aaa=""

def getit():
    print thread.get_ident(), "getit response.id is", response.abc

def myfunc(string, sleeptime, *args):
    while 1:
        response.abc = random.randrange(1,20)
        print string, "getit response.id is", response.abc
        arg1 = random.randrange(1,6)
        time.sleep(arg1)
        getit()
        time.sleep(sleeptime)
        if aaa == "quit":
            sys.exit()

def test(x, y):
    print x, y
    global aaa
Пример #11
0
 def __init__(self):
     self.thread_local = thread._local()
     self.thread_local.data = {}
     self.thread_local.keys = []
Пример #12
0
            self = getcurrent()
        f = _continulet.__reduce__(self)[2][0]
        if not f:
            return None
        return f.f_back.f_back.f_back   # go past start(), __switch(), switch()

# ____________________________________________________________
# Internal stuff

try:
    from thread import _local
except ImportError:
    class _local(object):    # assume no threads
        pass

_tls = _local()

def _green_create_main():
    # create the main greenlet for this thread
    _tls.current = None
    gmain = greenlet.__new__(greenlet)
    gmain._greenlet__main = True
    gmain._greenlet__started = True
    assert gmain.parent is None
    _tls.main = gmain
    _tls.current = gmain

def _greenlet_start(greenlet, args):
    _tls.current = greenlet
    try:
        res = greenlet.run(*args)
Пример #13
0
    class Popen(object):
        """
        Start a subprocess to run the code of a process object
        """
        _tls = thread._local()

        def __init__(self, process_obj):
            rfd, wfd = os.pipe()
            rhandle = duplicate(msvcrt.get_osfhandle(rfd), inheritable=True)
            os.close(rfd)
            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)
            self.pid = pid
            self.returncode = None
            self._handle = hp
            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()

            return

        @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

            return
Пример #14
0
    import imp, thread, msvcrt, _subprocess
    from os.path import dirname, splitext, basename, abspath

    try:
        from dill import dump, load, HIGHEST_PROTOCOL
    except ImportError:
        from cPickle import dump, load, HIGHEST_PROTOCOL
    from processing._processing import win32
    from processing._processing import _hInterruptEvent, _main_thread_ident
    from processing.finalize import Finalize

    TERMINATE = 0x10000
    WINEXE = sys.platform == "win32" and getattr(sys, "frozen", False)

    exit = win32.ExitProcess
    tls = thread._local()

    def thisThreadIsSpawning():
        return getattr(tls, "is_spawning", False)

    #
    # We define a Popen class similar to the one from subprocess, but
    # whose constructor takes a process object as its argument, and which
    # has terminate() and waitTimeout() methods.
    #

    class Popen(object):
        """
        Start a subprocess to run the code of a process object
        """
Пример #15
0
__author__ = 'Daniel.Lee'
# -*- coding: cp936 -*-
import thread
import random
import time
import sys

aaa = ''  #初始用户输入变量,这个是所有线程里的全局变量,不是单个线程里的全局变量
#线程区域
##这得定义在主块里,不可在函数里定义,要不也就只是个"私有变量"了.
#下面就是"单个线程里的全局变量的定义方法,以下的response.abc就是一个这种变量了.
response = thread._local()  #这句得在主块里定义,
response.abc = 1  #但这句也定义在主块里就相当于没定义过了,相看下面的#AA3


#非多线程程序可直接用'aaa'等来命名全局变量,但是"线程里的全局变量"就得是XXX.aaa了
def getit():
    #多个线程共用此函数,此函数所调用的"response.abc"就是各个线程里自已的"全局变量"
    #所以可引用,但不会被其它线程修改
    print thread.get_ident(), "getit response.id is", response.abc


def myfunction(string, sleeptime, *args):
    while 1:
        #AA3 #要在定里定义才行......在这个函数块里,不是主块里..
        response.abc = random.randrange(1, 20)  # 这里不可没有,主块里那句可没有,有也不起作用...
        print string, "response.abc is", response.abc
        arg1 = random.randrange(1, 6)
        time.sleep(arg1)
        getit()
        time.sleep(sleeptime)  #sleep for a specified amount of time.
Пример #16
0
__author__ = 'Daniel.Lee'
# -*- coding: cp936 -*-
import thread
import random
import time
import sys

aaa='' #初始用户输入变量,这个是所有线程里的全局变量,不是单个线程里的全局变量
#线程区域
##这得定义在主块里,不可在函数里定义,要不也就只是个"私有变量"了.
#下面就是"单个线程里的全局变量的定义方法,以下的response.abc就是一个这种变量了.
response=thread._local()           #这句得在主块里定义,
response.abc=1    #但这句也定义在主块里就相当于没定义过了,相看下面的#AA3
#非多线程程序可直接用'aaa'等来命名全局变量,但是"线程里的全局变量"就得是XXX.aaa了
def getit():
    #多个线程共用此函数,此函数所调用的"response.abc"就是各个线程里自已的"全局变量"
    #所以可引用,但不会被其它线程修改
    print thread.get_ident(),"getit response.id is",response.abc
def myfunction(string,sleeptime,*args):
    while 1:
#AA3 #要在定里定义才行......在这个函数块里,不是主块里..
        response.abc=random.randrange(1,20)    # 这里不可没有,主块里那句可没有,有也不起作用...
        print string,"response.abc is",response.abc
        arg1=random.randrange(1,6)
        time.sleep(arg1)
        getit()
        time.sleep(sleeptime) #sleep for a specified amount of time.
        if aaa=='quit':
            sys.exit()
def test(x,y):
    print x,y
Пример #17
0
    class Popen(object):

        _tls = thread._local()

        def __init__(self, process_obj):
            # register reducers
            from billiard import connection  # noqa
            _Django_old_layout_hack__save()
            sys.stdout.flush()
            sys.stderr.flush()
            self.returncode = None
            r, w = os.pipe()
            self.sentinel = r

            if _forking_is_enabled:
                self.pid = os.fork()
                if self.pid == 0:
                    os.close(r)
                    if 'random' in sys.modules:
                        import random
                        random.seed()
                    code = process_obj._bootstrap()
                    os._exit(code)
            else:
                from_parent_fd, to_child_fd = os.pipe()
                cmd = get_command_line() + [str(from_parent_fd)]

                self.pid = os.fork()
                if self.pid == 0:
                    os.close(r)
                    os.close(to_child_fd)
                    os.execv(sys.executable, cmd)

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

            # `w` will be closed when the child exits, at which point `r`
            # will become ready for reading (using e.g. select()).
            os.close(w)
            util.Finalize(self, os.close, (self.sentinel,))

        def poll(self, flag=os.WNOHANG):
            if self.returncode is None:
                try:
                    pid, sts = os.waitpid(self.pid, flag)
                except os.error:
                    # Child process not yet created. See #1731717
                    # e.errno == errno.ECHILD == 10
                    return None
                if pid == self.pid:
                    if os.WIFSIGNALED(sts):
                        self.returncode = -os.WTERMSIG(sts)
                    else:
                        assert os.WIFEXITED(sts)
                        self.returncode = os.WEXITSTATUS(sts)
            return self.returncode

        def wait(self, timeout=None):
            if self.returncode is None:
                if timeout is not None:
                    r = _select([self.sentinel], [], [], timeout)[0]
                    if not r:
                        return None
                # This shouldn't block if select() returned successfully.
                return self.poll(os.WNOHANG if timeout == 0.0 else 0)
            return self.returncode

        def terminate(self):
            if self.returncode is None:
                try:
                    os.kill(self.pid, signal.SIGTERM)
                except OSError:
                    if self.wait(timeout=0.1) is None:
                        raise

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

        @staticmethod
        def duplicate_for_child(handle):
            return handle
Пример #18
0
    class Popen(object):
        '''
        Start a subprocess to run the code of a process object
        '''
        _tls = thread._local()

        def __init__(self, process_obj):
            _Django_old_layout_hack__save()
            # 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
            )
            close(ht) if isinstance(ht, int_types) else ht.Close()
            (close(rhandle) if isinstance(rhandle, int_types)
             else rhandle.Close())

            # set attributes of self
            self.pid = pid
            self.returncode = None
            self._handle = hp
            self.sentinel = int(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