當前位置: 首頁>>代碼示例>>Python>>正文


Python _thread.allocate_lock方法代碼示例

本文整理匯總了Python中_thread.allocate_lock方法的典型用法代碼示例。如果您正苦於以下問題:Python _thread.allocate_lock方法的具體用法?Python _thread.allocate_lock怎麽用?Python _thread.allocate_lock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在_thread的用法示例。


在下文中一共展示了_thread.allocate_lock方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _run_in_multiple_threads

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
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] 
開發者ID:johncsnyder,項目名稱:SwiftKitten,代碼行數:26,代碼來源:test_verify.py

示例2: __init__

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
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('') 
開發者ID:zhuyifei1999,項目名稱:guppy3,代碼行數:18,代碼來源:Remote.py

示例3: test_repr_stopped

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
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 
開發者ID:IronLanguages,項目名稱:ironpython3,代碼行數:27,代碼來源:test_threading.py

示例4: test_with_traceback

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
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')]) 
開發者ID:IronLanguages,項目名稱:ironpython3,代碼行數:22,代碼來源:test_traceback.py

示例5: __init__

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
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 
開發者ID:kuri65536,項目名稱:python-for-android,代碼行數:25,代碼來源:SessionCache.py

示例6: __init__

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
def __init__(self) :
        self._processing   = False
        self._threadsCount = 0
        self._opLock       = allocate_lock()
        self._asyncSockets = { }
        self._readList     = [ ]
        self._writeList    = [ ]
        self._handlingList = [ ]

    # ------------------------------------------------------------------------ 
開發者ID:jczic,項目名稱:MicroWebSrv2,代碼行數:12,代碼來源:XAsyncSockets.py

示例7: allocate_lock

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
def allocate_lock():
    """Dummy implementation of _thread.allocate_lock()."""
    return LockType() 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:5,代碼來源:_dummy_thread.py

示例8: __init__

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
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 IOError('"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() 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:14,代碼來源:_io.py

示例9: __init__

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
def __init__(self, socket, httpClient, httpResponse, maxRecvLen, threaded, acceptCallback) :
        self._socket            = socket
        self._httpCli           = httpClient
        self._closed            = True
        self._lock              = allocate_lock()
        self.RecvTextCallback   = None
        self.RecvBinaryCallback = None
        self.ClosedCallback     = None

        if hasattr(socket, 'read'):   # MicroPython
            self._socketfile = self._socket
        else:   # CPython
            self._socketfile = self._socket.makefile('rwb')

        if self._handshake(httpResponse) :
            self._ctrlBuf = MicroWebSocket._tryAllocByteArray(0x7D)
            self._msgBuf  = MicroWebSocket._tryAllocByteArray(maxRecvLen)
            if self._ctrlBuf and self._msgBuf :
                self._msgType = None
                self._msgLen  = 0
                if threaded :
                    if MicroWebSocket._tryStartThread(self._wsProcess, (acceptCallback, )) :
                        return
                else :
                    self._wsProcess(acceptCallback)
                    return
            print("MicroWebSocket : Out of memory on new WebSocket connection.")
        try :
            if self._socketfile is not self._socket:
                self._socketfile.close()
            self._socket.close()
        except :
            pass

    # ============================================================================
    # ===( Functions )============================================================
    # ============================================================================ 
開發者ID:jczic,項目名稱:MicroWebSrv,代碼行數:39,代碼來源:microWebSocket.py

示例10: check_main_thread_id_multiple_threads

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
def check_main_thread_id_multiple_threads():
    import attach_script
    import sys
    import time
    assert 'threading' not in sys.modules
    try:
        import thread
    except ImportError:
        import _thread as thread

    lock = thread.allocate_lock()
    lock2 = thread.allocate_lock()

    def method():
        lock2.acquire()
        with lock:
            pass  # Will only finish when lock is released.

    with lock:
        thread.start_new_thread(method, ())
        while not lock2.locked():
            time.sleep(.1)

        wait_for_condition(lambda: len(sys._current_frames()) == 2)

        main_thread_id, log_msg = attach_script.get_main_thread_id(None)
        assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident())
        assert not log_msg
        assert 'threading' not in sys.modules
    wait_for_condition(lambda: len(sys._current_frames()) == 1) 
開發者ID:fabioz,項目名稱:PyDev.Debugger,代碼行數:32,代碼來源:_pydevd_test_find_main_thread_id.py

示例11: check_fix_main_thread_id_multiple_threads

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
def check_fix_main_thread_id_multiple_threads():
    import attach_script
    import sys
    import time
    assert 'threading' not in sys.modules
    try:
        import thread
    except ImportError:
        import _thread as thread

    lock = thread.allocate_lock()
    lock2 = thread.allocate_lock()

    def method():
        lock2.acquire()
        import threading  # Note: imported on wrong thread
        assert threading.current_thread().ident == thread.get_ident()
        assert threading.current_thread() is attach_script.get_main_thread_instance(threading)

        attach_script.fix_main_thread_id()

        assert threading.current_thread().ident == thread.get_ident()
        assert threading.current_thread() is not attach_script.get_main_thread_instance(threading)

        with lock:
            pass  # Will only finish when lock is released.

    with lock:
        thread.start_new_thread(method, ())
        while not lock2.locked():
            time.sleep(.1)

        wait_for_condition(lambda: len(sys._current_frames()) == 2)

        main_thread_id, log_msg = attach_script.get_main_thread_id(None)
        assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident())
        assert not log_msg
        assert 'threading' in sys.modules
        import threading
        assert threading.current_thread().ident == main_thread_id
    wait_for_condition(lambda: len(sys._current_frames()) == 1) 
開發者ID:fabioz,項目名稱:PyDev.Debugger,代碼行數:43,代碼來源:_pydevd_test_find_main_thread_id.py

示例12: check_win_threads

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
def check_win_threads():
    import sys
    if sys.platform != 'win32':
        return

    import attach_script
    import time
    assert 'threading' not in sys.modules
    try:
        import thread
    except ImportError:
        import _thread as thread
    from ctypes import windll, WINFUNCTYPE, c_uint32, c_void_p, c_size_t

    ThreadProc = WINFUNCTYPE(c_uint32, c_void_p)

    lock = thread.allocate_lock()
    lock2 = thread.allocate_lock()

    @ThreadProc
    def method(_):
        lock2.acquire()
        with lock:
            pass  # Will only finish when lock is released.
        return 0

    with lock:
        windll.kernel32.CreateThread(None, c_size_t(0), method, None, c_uint32(0), None)
        while not lock2.locked():
            time.sleep(.1)

        wait_for_condition(lambda: len(sys._current_frames()) == 2)

        main_thread_id, log_msg = attach_script.get_main_thread_id(None)
        assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident())
        assert not log_msg
        assert 'threading' not in sys.modules
    wait_for_condition(lambda: len(sys._current_frames()) == 1) 
開發者ID:fabioz,項目名稱:PyDev.Debugger,代碼行數:40,代碼來源:_pydevd_test_find_main_thread_id.py

示例13: __init__

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
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 
開發者ID:caronc,項目名稱:nzb-subliminal,代碼行數:12,代碼來源:rrule.py

示例14: __init__

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
def __init__(self, pool=None):
        self.pool = pool
        self.fd = 0
        self.pool_lock = _thread.allocate_lock()
        logger.critical('...') 
開發者ID:alcarithemad,項目名稱:zfsp,代碼行數:7,代碼來源:zfuse.py

示例15: __init__

# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import allocate_lock [as 別名]
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() 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:14,代碼來源:_pyio.py


注:本文中的_thread.allocate_lock方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。