我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用_thread.allocate_lock()。
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]
def __init__(self, ufc, node, iomap, cmd_pend_size = 2, timeout = 1): self.ports = { 'cmd_async': {'dir': 'in', 'type': 'topic', 'callback': self.cmd_async_cb}, 'cmd_sync': {'dir': 'in', 'type': 'service', 'callback': self.cmd_sync_cb}, 'report': {'dir': 'out', 'type': 'topic'}, 'status': {'dir': 'out', 'type': 'topic'}, # report lost, etc... 'service': {'dir': 'in', 'type': 'service', 'callback': self.service_cb}, 'packet_in': {'dir': 'in', 'type': 'topic', 'callback': self.packet_in_cb}, 'packet_out': {'dir': 'out', 'type': 'topic'}, } self.node = node self.logger = logging.getLogger('uf.' + node.replace('/', '.')) self.cmd_pend = {} self.cmd_pend_size = cmd_pend_size self.cmd_pend_c = threading.Condition() self.timeout = timeout self.cnt_lock = _thread.allocate_lock() self.cnt = 1 # no reply if cnt == 0, FIXME ufc.node_init(node, self.ports, iomap)
def __init__(self): self.debugApplication = None self.debuggingThread = None self.debuggingThreadStateHandle = None self.stackSnifferCookie = self.stackSniffer = None self.codeContainerProvider = None self.debuggingThread = None self.breakFlags = None self.breakReason = None self.appDebugger = None self.appEventConnection = None self.logicalbotframe = None # Anything at this level or below does not exist! self.currentframe = None # The frame we are currently in. self.recursiveData = [] # Data saved for each reentery on this thread. bdb.Bdb.__init__(self) self._threadprotectlock = _thread.allocate_lock() self.reset()
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
def main(): print('starting --',ctime()) locks = [] nloops = range(len(loops)) for i in nloops: lock = _thread.allocate_lock() # ????? lock.acquire() # ????? locks.append(lock) for i in nloops: _thread.start_new_thread(loop,(i,loops[i],locks[i])) for i in nloops: while locks[i].locked(): pass print('all Done---',ctime())
def __init__(self, srcShadowName, srcIsPersistentSubscribe, srcShadowManager): if srcShadowName is None or srcIsPersistentSubscribe is None or srcShadowManager is None: raise TypeError("None type inputs detected.") self._shadowName = srcShadowName # Tool handler self._shadowManagerHandler = srcShadowManager self._basicJSONParserHandler = _basicJSONParser() # Properties self._isPersistentSubscribe = srcIsPersistentSubscribe self._lastVersionInSync = -1 # -1 means not initialized self._isGetSubscribed = False self._isUpdateSubscribed = False self._isDeleteSubscribed = False self._shadowSubscribeCallbackTable = dict() self._shadowSubscribeCallbackTable["get"] = None self._shadowSubscribeCallbackTable["delete"] = None self._shadowSubscribeCallbackTable["update"] = None self._shadowSubscribeCallbackTable["delta"] = None self._shadowSubscribeStatusTable = dict() self._shadowSubscribeStatusTable["get"] = 0 self._shadowSubscribeStatusTable["delete"] = 0 self._shadowSubscribeStatusTable["update"] = 0 self._tokenPool = dict() self._dataStructureLock = _thread.allocate_lock()
def __init__(self, clientID, cleanSession, protocol): self.client_id = clientID self._cleanSession = cleanSession self._protocol = protocol self._userdata = None self._user = "" self._password = "" self._keepAliveInterval = 60 self._will = False self._will_topic = "" self._will_message= None self._will_qos = 0 self._will_retain = False self._connectdisconnectTimeout = 30 self._mqttOperationTimeout = 5 self._topic_callback_queue=[] self._callback_mutex=_thread.allocate_lock() self._pid = 0 self._subscribeSent = False self._unsubscribeSent = False self._baseReconnectTimeSecond=1 self._maximumReconnectTimeSecond=32 self._minimumConnectTimeSecond=20 self._msgHandler=msgHandler.MsgHandler(self._recv_callback)
def __init__(self, id, frequency, datarate, ssid, password, server, port, ntp='pool.ntp.org', ntp_period=3600): self.id = id self.frequency = frequency self.sf = self._dr_to_sf(datarate) self.ssid = ssid self.password = password self.server = server self.port = port self.ntp = ntp self.ntp_period = ntp_period self.rxnb = 0 self.rxok = 0 self.rxfw = 0 self.dwnb = 0 self.txnb = 0 self.stat_alarm = None self.pull_alarm = None self.uplink_alarm = None self.udp_lock = _thread.allocate_lock() self.lora = None self.lora_sock = None
def allocate_lock(): """Dummy implementation of _thread.allocate_lock().""" return LockType()
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'))
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() ########################################################################
def __init__(self, socket, callback): self.socket = socket self.seq = 0 self.callback = callback self.lock = thread.allocate_lock() # start the testing reader thread loop self.test_thread_id = thread.start_new_thread(self.readSocket, ())
def __init__(self): self.default_mode = BREAK_MODE_UNHANDLED self.break_on = { } self.handler_cache = dict(self.BUILT_IN_HANDLERS) self.handler_lock = thread.allocate_lock() self.add_exception('exceptions.IndexError', BREAK_MODE_NEVER) self.add_exception('builtins.IndexError', BREAK_MODE_NEVER) self.add_exception('exceptions.KeyError', BREAK_MODE_NEVER) self.add_exception('builtins.KeyError', BREAK_MODE_NEVER) self.add_exception('exceptions.AttributeError', BREAK_MODE_NEVER) self.add_exception('builtins.AttributeError', BREAK_MODE_NEVER) self.add_exception('exceptions.StopIteration', BREAK_MODE_NEVER) self.add_exception('builtins.StopIteration', BREAK_MODE_NEVER) self.add_exception('exceptions.GeneratorExit', BREAK_MODE_NEVER) self.add_exception('builtins.GeneratorExit', BREAK_MODE_NEVER)
def __init__(self, id = None): if id is not None: self.id = id else: self.id = thread.get_ident() self._events = {'call' : self.handle_call, 'line' : self.handle_line, 'return' : self.handle_return, 'exception' : self.handle_exception, 'c_call' : self.handle_c_call, 'c_return' : self.handle_c_return, 'c_exception' : self.handle_c_exception, } self.cur_frame = None self.stepping = STEPPING_NONE self.unblock_work = None self._block_lock = thread.allocate_lock() self._block_lock.acquire() self._block_starting_lock = thread.allocate_lock() self._is_blocked = False self._is_working = False self.stopped_on_line = None self.detach = False self.trace_func = self.trace_func # replace self.trace_func w/ a bound method so we don't need to re-create these regularly self.prev_trace_func = None self.trace_func_stack = [] self.reported_process_loaded = False self.django_stepping = None self.is_sending = False # stackless changes if stackless is not None: self._stackless_attach() if sys.platform == 'cli': self.frames = []
def __init__(self): self.lock = thread.allocate_lock()
def __init__(self, path): self.path = path self.subs = {} # format: 'node: handle, ...' self.pubs = {} #self.pub_lock = _thread.allocate_lock()
def __init__ (self, logger = None): r, w = os.pipe() self.trigger = w self.logger = logger asyncore.file_dispatcher.__init__ (self, r) self.lock = _thread.allocate_lock() self.thunks = []
def __init__ (self, logger = None): self.logger = logger sock_class = socket.socket a = sock_class (socket.AF_INET, socket.SOCK_STREAM) w = sock_class (socket.AF_INET, socket.SOCK_STREAM) try: a.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, a.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 ) except socket.error: pass # tricky: get a pair of connected sockets a.bind (self.address) a.listen (1) w.setblocking (0) try: w.connect (self.address) except: pass r, addr = a.accept() a.close() w.setblocking (1) self.trigger = w asyncore.dispatcher.__init__ (self, r) self.lock = _thread.allocate_lock() self.thunks = [] self._trigger_connected = 0
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
def test(self): self.lock = _thread.allocate_lock() for i in range(0, 10): _thread.start_new_thread(self.runnable, ())
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)
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()
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): if not raw.writable(): raise IOError('"raw" argument must be writable.') _BufferedIOMixin.__init__(self, raw) if buffer_size <= 0: raise ValueError("invalid buffer size") if max_buffer_size is not None: warnings.warn("max_buffer_size is deprecated", DeprecationWarning, self._warning_stack_offset) self.buffer_size = buffer_size self._write_buf = bytearray() self._write_lock = Lock()
def __init__(self, id, frequency, datarate, ssid, password, server, port, ntp_server='pool.ntp.org', ntp_period=3600): self.id = id self.server = server self.port = port self.frequency = frequency self.datarate = datarate self.ssid = ssid self.password = password self.ntp_server = ntp_server self.ntp_period = ntp_period self.server_ip = None self.rxnb = 0 self.rxok = 0 self.rxfw = 0 self.dwnb = 0 self.txnb = 0 self.sf = self._dr_to_sf(self.datarate) self.bw = self._dr_to_bw(self.datarate) self.stat_alarm = None self.pull_alarm = None self.uplink_alarm = None self.wlan = None self.sock = None self.udp_stop = False self.udp_lock = _thread.allocate_lock() self.lora = None self.lora_sock = None self.rtc = machine.RTC()
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): if not raw.writable(): raise IOError('"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()
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.assertTrue(t._tstate_lock is None)
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()
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()
def __init__(self): self.default_mode = BREAK_MODE_UNHANDLED self.break_on = { } self.handler_cache = dict(self.BUILT_IN_HANDLERS) self.handler_lock = thread.allocate_lock() self.AddException('exceptions.IndexError', BREAK_MODE_NEVER) self.AddException('exceptions.KeyError', BREAK_MODE_NEVER) self.AddException('exceptions.AttributeError', BREAK_MODE_NEVER) self.AddException('exceptions.StopIteration', BREAK_MODE_NEVER) self.AddException('exceptions.GeneratorExit', BREAK_MODE_NEVER)