Python _thread.allocate_lock() Examples

The following are 30 code examples of _thread.allocate_lock(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module _thread , or try the search function .
Example #1
Source File: test_verify.py    From SwiftKitten with MIT License 7 votes vote down vote up
def _run_in_multiple_threads(test1):
    test1()
    import sys
    try:
        import thread
    except ImportError:
        import _thread as thread
    errors = []
    def wrapper(lock):
        try:
            test1()
        except:
            errors.append(sys.exc_info())
        lock.release()
    locks = []
    for i in range(10):
        _lock = thread.allocate_lock()
        _lock.acquire()
        thread.start_new_thread(wrapper, (_lock,))
        locks.append(_lock)
    for _lock in locks:
        _lock.acquire()
        if errors:
            raise errors[0][1] 
Example #2
Source File: test_traceback.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_with_traceback(self):
        line_num=getlineno(lambda _: None)
        from _thread import allocate_lock
        def f():
            g()

        def g():
            h()

        def h():
            raise Exception('hello!!')

        try:
            with allocate_lock():
                f()
        except:
            self.assert_traceback([(line_num + 13, 30, FILE, 'test_with_traceback'),
                              (line_num + 3, 3, FILE, 'f'),
                              (line_num + 6, 3, FILE, 'g'),
                              (line_num + 9, 3, FILE, 'h')]) 
Example #3
Source File: Remote.py    From guppy3 with MIT License 6 votes vote down vote up
def __init__(self, target, port=None):
        cmd.Cmd.__init__(self)
        if port is None:
            port = HEAPYPORT
        self.server_address = (LOCALHOST, port)
        self.target = target
        target.close = target.sys.modules['guppy.heapy.Remote'].IsolatedCaller(
        # target.close = IsolatedCaller(
            self.asynch_close)
        self.socket = None
        self.isclosed = 0
        self.closelock = _thread.allocate_lock()

        self.intlocals = {
        }
        self.do_reset('') 
Example #4
Source File: SessionCache.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def __init__(self, maxEntries=10000, maxAge=14400):
        """Create a new SessionCache.

        @type maxEntries: int
        @param maxEntries: The maximum size of the cache.  When this
        limit is reached, the oldest sessions will be deleted as
        necessary to make room for new ones.  The default is 10000.

        @type maxAge: int
        @param maxAge:  The number of seconds before a session expires
        from the cache.  The default is 14400 (i.e. 4 hours)."""

        self.lock = _thread.allocate_lock()

        # Maps sessionIDs to sessions
        self.entriesDict = {}

        #Circular list of (sessionID, timestamp) pairs
        self.entriesList = [(None,None)] * maxEntries

        self.firstIndex = 0
        self.lastIndex = 0
        self.maxAge = maxAge 
Example #5
Source File: test_verify1.py    From SwiftKitten with MIT License 6 votes vote down vote up
def _run_in_multiple_threads(test1):
    test1()
    import sys
    try:
        import thread
    except ImportError:
        import _thread as thread
    errors = []
    def wrapper(lock):
        try:
            test1()
        except:
            errors.append(sys.exc_info())
        lock.release()
    locks = []
    for i in range(10):
        _lock = thread.allocate_lock()
        _lock.acquire()
        thread.start_new_thread(wrapper, (_lock,))
        locks.append(_lock)
    for _lock in locks:
        _lock.acquire()
        if errors:
            raise errors[0][1] 
Example #6
Source File: test_threading.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_repr_stopped(self):
        # Verify that "stopped" shows up in repr(Thread) appropriately.
        started = _thread.allocate_lock()
        finish = _thread.allocate_lock()
        started.acquire()
        finish.acquire()
        def f():
            started.release()
            finish.acquire()
        t = threading.Thread(target=f)
        t.start()
        started.acquire()
        self.assertIn("started", repr(t))
        finish.release()
        # "stopped" should appear in the repr in a reasonable amount of time.
        # Implementation detail:  as of this writing, that's trivially true
        # if .join() is called, and almost trivially true if .is_alive() is
        # called.  The detail we're testing here is that "stopped" shows up
        # "all on its own".
        LOOKING_FOR = "stopped"
        for i in range(500):
            if LOOKING_FOR in repr(t):
                break
            time.sleep(0.01)
        self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds 
Example #7
Source File: _pyio.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
        """Create a new buffered reader using the given readable raw IO object.
        """
        if not raw.readable():
            raise OSError('"raw" argument must be readable.')

        _BufferedIOMixin.__init__(self, raw)
        if buffer_size <= 0:
            raise ValueError("invalid buffer size")
        self.buffer_size = buffer_size
        self._reset_read_buf()
        self._read_lock = Lock() 
Example #8
Source File: _dummy_thread.py    From android_universal with MIT License 5 votes vote down vote up
def allocate_lock():
    """Dummy implementation of _thread.allocate_lock()."""
    return LockType() 
Example #9
Source File: _pyio.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
        if not raw.writable():
            raise OSError('"raw" argument must be writable.')

        _BufferedIOMixin.__init__(self, raw)
        if buffer_size <= 0:
            raise ValueError("invalid buffer size")
        self.buffer_size = buffer_size
        self._write_buf = bytearray()
        self._write_lock = Lock() 
Example #10
Source File: recipe-577825.py    From code with MIT License 5 votes vote down vote up
def __init__(self, immediate=False, silent=False):
        "Initializes _Lock instance with internal mechanism."
        self.__lock = _thread.allocate_lock()
        self.__verbose = silent
        if immediate:
            self.acquire()

    ######################################################################## 
Example #11
Source File: test_threading.py    From android_universal with MIT License 5 votes vote down vote up
def test_finalize_runnning_thread(self):
        # Issue 1402: the PyGILState_Ensure / _Release functions may be called
        # very late on python exit: on deallocation of a running thread for
        # example.
        import_module("ctypes")

        rc, out, err = assert_python_failure("-c", """if 1:
            import ctypes, sys, time, _thread

            # This lock is used as a simple event variable.
            ready = _thread.allocate_lock()
            ready.acquire()

            # Module globals are cleared before __del__ is run
            # So we save the functions in class dict
            class C:
                ensure = ctypes.pythonapi.PyGILState_Ensure
                release = ctypes.pythonapi.PyGILState_Release
                def __del__(self):
                    state = self.ensure()
                    self.release(state)

            def waitingThread():
                x = C()
                ready.release()
                time.sleep(100)

            _thread.start_new_thread(waitingThread, ())
            ready.acquire()  # Be sure the other thread is waiting.
            sys.exit(42)
            """)
        self.assertEqual(rc, 42) 
Example #12
Source File: test_threading.py    From android_universal with MIT License 5 votes vote down vote up
def test_tstate_lock(self):
        # Test an implementation detail of Thread objects.
        started = _thread.allocate_lock()
        finish = _thread.allocate_lock()
        started.acquire()
        finish.acquire()
        def f():
            started.release()
            finish.acquire()
            time.sleep(0.01)
        # The tstate lock is None until the thread is started
        t = threading.Thread(target=f)
        self.assertIs(t._tstate_lock, None)
        t.start()
        started.acquire()
        self.assertTrue(t.is_alive())
        # The tstate lock can't be acquired when the thread is running
        # (or suspended).
        tstate_lock = t._tstate_lock
        self.assertFalse(tstate_lock.acquire(timeout=0), False)
        finish.release()
        # When the thread ends, the state_lock can be successfully
        # acquired.
        self.assertTrue(tstate_lock.acquire(timeout=5), False)
        # But is_alive() is still True:  we hold _tstate_lock now, which
        # prevents is_alive() from knowing the thread's end-of-life C code
        # is done.
        self.assertTrue(t.is_alive())
        # Let is_alive() find out the C code is done.
        tstate_lock.release()
        self.assertFalse(t.is_alive())
        # And verify the thread disposed of _tstate_lock.
        self.assertIsNone(t._tstate_lock)
        t.join() 
Example #13
Source File: pipetool.py    From arissploit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *pipes):
        self.active_pipes = set()
        self.active_sources = set()
        self.active_drains = set()
        self.active_sinks = set()
        self._add_pipes(*pipes)
        self.thread_lock = _thread.allocate_lock()
        self.command_lock = _thread.allocate_lock()
        self.__fdr,self.__fdw = os.pipe()
        self.threadid = None 
Example #14
Source File: pipetool.py    From kamene with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *pipes):
        self.active_pipes = set()
        self.active_sources = set()
        self.active_drains = set()
        self.active_sinks = set()
        self._add_pipes(*pipes)
        self.thread_lock = _thread.allocate_lock()
        self.command_lock = _thread.allocate_lock()
        self.__fdr,self.__fdw = os.pipe()
        self.threadid = None 
Example #15
Source File: test_threading.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_tstate_lock(self):
        # Test an implementation detail of Thread objects.
        started = _thread.allocate_lock()
        finish = _thread.allocate_lock()
        started.acquire()
        finish.acquire()
        def f():
            started.release()
            finish.acquire()
            time.sleep(0.01)
        # The tstate lock is None until the thread is started
        t = threading.Thread(target=f)
        self.assertIs(t._tstate_lock, None)
        t.start()
        started.acquire()
        self.assertTrue(t.is_alive())
        # The tstate lock can't be acquired when the thread is running
        # (or suspended).
        tstate_lock = t._tstate_lock
        self.assertFalse(tstate_lock.acquire(timeout=0), False)
        finish.release()
        # When the thread ends, the state_lock can be successfully
        # acquired.
        self.assertTrue(tstate_lock.acquire(timeout=5), False)
        # But is_alive() is still True:  we hold _tstate_lock now, which
        # prevents is_alive() from knowing the thread's end-of-life C code
        # is done.
        self.assertTrue(t.is_alive())
        # Let is_alive() find out the C code is done.
        tstate_lock.release()
        self.assertFalse(t.is_alive())
        # And verify the thread disposed of _tstate_lock.
        self.assertIsNone(t._tstate_lock) 
Example #16
Source File: demo_thread.py    From SmallReptileTraining with MIT License 5 votes vote down vote up
def test(self):
        self.lock = _thread.allocate_lock()
        for i in range(0, 10):
            _thread.start_new_thread(self.runnable, ()) 
Example #17
Source File: BaseDB.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, filename, type):
        self.type = type
        self.filename = filename
        if self.filename:
            self.db = None
        else:
            self.db = {}
        self.lock = _thread.allocate_lock() 
Example #18
Source File: _dummy_thread.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def allocate_lock():
    """Dummy implementation of _thread.allocate_lock()."""
    return LockType() 
Example #19
Source File: rrule.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def __init__(self, cache=False):
        if cache:
            self._cache = []
            self._cache_lock = _thread.allocate_lock()
            self._cache_gen  = self._iter()
            self._cache_complete = False
        else:
            self._cache = None
            self._cache_complete = False
        self._len = None 
Example #20
Source File: _dummy_thread.py    From scylla with Apache License 2.0 5 votes vote down vote up
def allocate_lock():
    """Dummy implementation of _thread.allocate_lock()."""
    return LockType() 
Example #21
Source File: recipe-577825.py    From code with MIT License 5 votes vote down vote up
def __add_transaction_support(self):
        "Add attributes so database can support transactions."
        self.__lock = _thread.allocate_lock()
        self.__extend_data()
        self.__locked = _View(None, lambda _: self.__data \
            .select('name', (lambda lock: lock.locked, 'lock')) \
            .as_(('<lambda>(lock)', 'locked')))
        self.__view = _View(None, lambda _: self._Database__view.value \
            .left_join(self.__locked.value, 'Lock', ROW.name == ROW.Lock.name) \
            .select('name', 'type', 'size', 'Lock.locked'), \
            ('Lock.locked', 'locked')) 
Example #22
Source File: recipe-577633.py    From code with MIT License 5 votes vote down vote up
def __init__(self, func, args, keywords):
            "Initialize the job's info and ready for execution."
            self.__func = func
            self.__args = args
            self.__keywords = keywords
            self.__error = False
            self.__mutex = _thread.allocate_lock()
            self.__mutex.acquire() 
Example #23
Source File: recipe-578151.py    From code with MIT License 5 votes vote down vote up
def __init__(self, func, args, kwargs):
        "Initializes instance from arguments and prepares to run."
        self.__func = func
        self.__args = args
        self.__kwargs = kwargs
        self.__mutex = _thread.allocate_lock()
        self.__mutex.acquire() 
Example #24
Source File: test_python25.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_thread_lock(self):
        import _thread

        temp_lock = _thread.allocate_lock()
        self.assertTrue(hasattr(temp_lock, "__enter__"))
        self.assertTrue(hasattr(temp_lock, "__exit__"))
        self.assertTrue(not temp_lock.locked())
        with temp_lock:
            self.assertTrue(temp_lock.locked())
        self.assertTrue(not temp_lock.locked())
        
        with _thread.allocate_lock(): pass 
Example #25
Source File: test_threading.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_finalize_runnning_thread(self):
        # Issue 1402: the PyGILState_Ensure / _Release functions may be called
        # very late on python exit: on deallocation of a running thread for
        # example.
        import_module("ctypes")

        rc, out, err = assert_python_failure("-c", """if 1:
            import ctypes, sys, time, _thread

            # This lock is used as a simple event variable.
            ready = _thread.allocate_lock()
            ready.acquire()

            # Module globals are cleared before __del__ is run
            # So we save the functions in class dict
            class C:
                ensure = ctypes.pythonapi.PyGILState_Ensure
                release = ctypes.pythonapi.PyGILState_Release
                def __del__(self):
                    state = self.ensure()
                    self.release(state)

            def waitingThread():
                x = C()
                ready.release()
                time.sleep(100)

            _thread.start_new_thread(waitingThread, ())
            ready.acquire()  # Be sure the other thread is waiting.
            sys.exit(42)
            """)
        self.assertEqual(rc, 42) 
Example #26
Source File: _pyio.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
        if not raw.writable():
            raise OSError('"raw" argument must be writable.')

        _BufferedIOMixin.__init__(self, raw)
        if buffer_size <= 0:
            raise ValueError("invalid buffer size")
        self.buffer_size = buffer_size
        self._write_buf = bytearray()
        self._write_lock = Lock() 
Example #27
Source File: _pyio.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
        """Create a new buffered reader using the given readable raw IO object.
        """
        if not raw.readable():
            raise OSError('"raw" argument must be readable.')

        _BufferedIOMixin.__init__(self, raw)
        if buffer_size <= 0:
            raise ValueError("invalid buffer size")
        self.buffer_size = buffer_size
        self._reset_read_buf()
        self._read_lock = Lock() 
Example #28
Source File: _dummy_thread.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def allocate_lock():
    """Dummy implementation of _thread.allocate_lock()."""
    return LockType() 
Example #29
Source File: console_util.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def InitializeErrorWatcher(self):
        from System.Threading import Thread, ThreadStart
        import _thread            
        self.errorLock = _thread.allocate_lock()
        self.errorString = ""
        th = Thread(ThreadStart(self.WatchErrorStream))
        th.IsBackground = True
        th.Start() 
Example #30
Source File: _pyio.py    From Imogen with MIT License 5 votes vote down vote up
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
        """Create a new buffered reader using the given readable raw IO object.
        """
        if not raw.readable():
            raise OSError('"raw" argument must be readable.')

        _BufferedIOMixin.__init__(self, raw)
        if buffer_size <= 0:
            raise ValueError("invalid buffer size")
        self.buffer_size = buffer_size
        self._reset_read_buf()
        self._read_lock = Lock()