def __init__(self, interval, function, args=None, kwargs=None, niter=0): """Init method. Inputs: - interval: time to wait between sucessive calls to method. - function: method to be executed. - args: tuple of positional arguments of method - kwargs: dictionary with keyword arguments of method. - niter: number of times to execute method. If niter is zero or None it will be executed indefinetly until stop is called. """ if args is None: args = tuple() if kwargs is None: kwargs = dict() super().__init__(daemon=True) self.interval = interval if not hasattr(function, '__call__'): raise TypeError('Argument "function" is not callable.') self.function = function self.args = args self.kwargs = kwargs self.niters = niter self.cur_iter = 0 self._stopped = _Event() self._unpaused = _Event() self._unpaused.set()
def __init__(self, name=None): """.""" super().__init__(name=name, daemon=True) self._evt_received = _Event() self._evt_ready = _Event() self._evt_ready.set() self._evt_stop = _Event() self.target = None self.args = tuple()
def __init__(self, interval, function, args=[], kwargs={}): _Thread.__init__(self) self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.finished = _Event()
def _prepareClients(self): self._joinerEvent = _Event() self._joinerEvent.clear() self._clientThreads = {} # use threading.Event() to command the threads to do actions self._requestRWlock = {} self._requestWOlock = {} self._readAccess = {} self._writeAccess = {} self._releaseRWlock = {} self._releaseWOlock = {} for threadName in [4, 6]: requestRW = _EventWithResult() requestWO = _EventWithResult() readAction = _EventWithResult() writeAction = _EventWithResult() releaseRW = _EventWithResult() releaseWO = _EventWithResult() threadObj = _Thread(target=self._clientThread, args=(threadName,), name="IPv%d" % threadName) self._requestRWlock[threadName] = requestRW self._requestWOlock[threadName] = requestWO self._readAccess[threadName] = readAction self._writeAccess[threadName] = writeAction self._releaseRWlock[threadName] = releaseRW self._releaseWOlock[threadName] = releaseWO self._clientThreads[threadName] = threadObj threadObj.start()
def _prepareClients(self): self._joinerEvent = _Event() self._joinerEvent.clear() self._clientThreads = {} # use threading.Event() to command the threads to do actions self._requestRWlock = {} self._requestWOlock = {} self._readAccess = {} self._writeAccess = {} self._releaseRWlock = {} self._releaseWOlock = {} for threadName in [4, 6]: requestRW = _EventWithResult() requestWO = _EventWithResult() readAction = _EventWithResult() writeAction = _EventWithResult() releaseRW = _EventWithResult() releaseWO = _EventWithResult() threadObj = _Thread(target=self._clientThread, args=(threadName, ), name="IPv%d" % threadName) self._requestRWlock[threadName] = requestRW self._requestWOlock[threadName] = requestWO self._readAccess[threadName] = readAction self._writeAccess[threadName] = writeAction self._releaseRWlock[threadName] = releaseRW self._releaseWOlock[threadName] = releaseWO self._clientThreads[threadName] = threadObj threadObj.start()
def _prepare_clients(self): self._joiner_event = _Event() self._joiner_event.clear() self._client_threads = {} # use threading.Event() to command the threads to do actions self._request_RW_lock = {} self._request_WO_lock = {} self._read_access = {} self._write_access = {} self._release_RW_lock = {} self._release_WO_lock = {} for thread_name in [4, 6]: request_RW = _EventWithResult() request_WO = _EventWithResult() read_action = _EventWithResult() write_action = _EventWithResult() release_RW = _EventWithResult() release_WO = _EventWithResult() thread_obj = _Thread(target=self._client_thread, args=(thread_name,), name="IPv{0:d}".format(thread_name)) self._request_RW_lock[thread_name] = request_RW self._request_WO_lock[thread_name] = request_WO self._read_access[thread_name] = read_action self._write_access[thread_name] = write_action self._release_RW_lock[thread_name] = release_RW self._release_WO_lock[thread_name] = release_WO self._client_threads[thread_name] = thread_obj thread_obj.start()
def retry_block(self): # Received a retry request that made it all the way up to the top. # First, check to see if any of the variables we've accessed have # been modified since we started; if they have, we need to restart # instead. with _global_lock: for item in self.check_values: item._check_clean() # Nope, none of them have changed. So now we create an event, # then add it to all of the vars we need to watch. e = _Event() for item in self.retry_values: item._add_retry_event(e) # Then we create a timer to let us know when our retry timeout (if any # calls made during this transaction indicated one) is up. Note that # _Timer does nothing when given a resume time of None, so we don't # need to worry about that here. timer = _Timer(e, self.resume_at) timer.start() # Then we wait. e.wait() # One of the vars was modified or our timeout expired. Now we go cancel # the timer (in case it was a change to one of our watched vars that # woke us up instead of a timeout) and remove ourselves from the vars' # events. timer.cancel() with _global_lock: for item in self.retry_values: item._remove_retry_event(e) # And then we restart. raise _Restart
def run_subprocess_old(pvs, send_pipe, recv_pipe): """Run subprocesses.""" # this timeout is needed to slip the orbit acquisition in case the # loop starts in the middle of the BPMs updates timeout = 15 / 1000 # in [s] def callback(*_, **kwargs): pvo = kwargs['cb_info'][1] # pvo._args['timestamp'] = _time.time() pvo.event.set() pvsobj = [] for pvn in pvs: pvo = _PV(pvn, connection_timeout=TIMEOUT) pvo.event = _Event() pvsobj.append(pvo) for pvo in pvsobj: pvo.wait_for_connection() pvo.add_callback(callback) while recv_pipe.recv(): out = [] tout = None for pvo in pvsobj: if pvo.connected and pvo.event.wait(timeout=tout): tout = timeout # out.append(pvo.timestamp) out.append(pvo.value) else: out.append(_np.nan) for pvo in pvsobj: pvo.event.clear() send_pipe.send(out)
def __init__(self, work_queue=None): _th.Thread.__init__(self) self.ev = _th._Event() self._event_status = False # 是否挂起 self.var_lock = True self.work_queue = work_queue self.mutex = _th.Lock() # 互斥锁 self.start()
def __init__(self): """.""" super().__init__() self._measuring = _Event() self.emittance_calculator = CalcEmmitance() self.image_processor = _ProcessImage() self.image_processor.readingorder = \ self.image_processor.ReadingOrder.CLike self._place = 'li' self._select_experimental_setup()
def run_subprocess(pvs, send_pipe, recv_pipe): """Run subprocesses.""" max_spread = 25 / 1000 # in [s] timeout = 50 / 1000 # in [s] ready_evt = _Event() tstamps = _np.full(len(pvs), _np.nan) def callback(*_, **kwargs): pvo = kwargs['cb_info'][1] # pvo._args['timestamp'] = _time.time() tstamps[pvo.index] = pvo.timestamp maxi = _bn.nanmax(tstamps) mini = _bn.nanmin(tstamps) if (maxi - mini) < max_spread: ready_evt.set() def conn_callback(pvname=None, conn=None, pv=None): if not conn: _log.warning(pvname + 'Disconnected') tstamps[pv.index] = _np.nan pvsobj = [] for i, pvn in enumerate(pvs): pvo = _PV(pvn, connection_timeout=TIMEOUT) pvo.index = i pvsobj.append(pvo) for pvo in pvsobj: pvo.wait_for_connection() for pvo in pvsobj: pvo.add_callback(callback) pvo.connection_callbacks.append(conn_callback) boo = True while boo or recv_pipe.recv(): boo = False ready_evt.clear() nok = 0.0 if not ready_evt.wait(timeout=timeout): nok = 1.0 out = [] for pvo in pvsobj: if not pvo.connected: out.append(_np.nan) continue # out.append(pvo.timestamp) out.append(pvo.value) out.append(nok) send_pipe.send(out)
def __init__(self, *args, **kwargs): """ Constructor __init__(ResultEvent) :since: v1.0.0 """ self._event = _Event(*args, **kwargs) """ Encapsulated event implementation """ self.timeout = Settings.get("global_event_timeout", 10) """
def __init__(self, acc, prefix='', callback=None): """Initialize the instance.""" super().__init__(acc, prefix=prefix, callback=callback) self._mode = self._csorb.SOFBMode.Offline self._sync_with_inj = False self.ref_orbs = { 'X': _np.zeros(self._csorb.nr_bpms), 'Y': _np.zeros(self._csorb.nr_bpms) } self._load_ref_orbs() self.raw_orbs = {'X': [], 'Y': []} self.raw_sporbs = {'X': [], 'Y': [], 'Sum': []} self.raw_mtorbs = {'X': [], 'Y': [], 'Sum': []} self._lock_raw_orbs = Lock() self.smooth_orb = {'X': None, 'Y': None} self.smooth_sporb = {'X': None, 'Y': None, 'Sum': None} self.smooth_mtorb = {'X': None, 'Y': None, 'Sum': None} self.offline_orbit = { 'X': _np.zeros(self._csorb.nr_bpms), 'Y': _np.zeros(self._csorb.nr_bpms) } self._smooth_npts = 1 self._smooth_meth = self._csorb.SmoothMeth.Average self._spass_mask = [0, 0] self._spass_average = 1 self._spass_th_acqbg = None self._spass_bgs = [dict() for _ in range(self._csorb.nr_bpms)] self._spass_usebg = self._csorb.SPassUseBg.NotUsing self._acqrate = self._csorb.MIN_SLOWORB_RATE self._oldacqrate = self._acqrate self._acqtrignrsamplespre = 0 self._acqtrignrsamplespost = 360 self._acqtrignrshots = 1 self._multiturnidx = 0 self._mturndownsample = 1 self._timevector = None self._ring_extension = 1 self.bpms = [BPM(name, callback) for name in self._csorb.bpm_names] self.timing = TimingConfig(acc, callback) self.new_orbit = _Event() if self.acc == 'SI': self._processes = [] self._mypipes_recv = [] self._mypipes_send = [] self._create_processes(nrprocs=16) self._orbit_thread = _Repeat(1 / self._acqrate, self._update_orbits, niter=0) self._orbit_thread.start() self._update_time_vector()
def test_close_hive(async_hive): run = _Event() @async_hive.streamer @async_generator async def stream(): await asyncio.sleep(1e-6) return 1 @async_hive.listener async def on_event(event): run.set() await asyncio.sleep(0) def close_after(): run.wait() async_hive.close() Thread(target=close_after).start() async_hive.run() assert run.is_set(), 'Did not run on_event before close'
def test_threaded_run(async_hive, async_bee_factory): stop = _Event() listener = async_bee_factory.create('listener') streamer = async_bee_factory.create('streamer') old_on_event = listener.on_event async def on_event(event): if not stop.is_set(): stop.set() else: async_hive.kill() await asyncio.sleep(0) return await old_on_event(event) listener.on_event = on_event async_hive.add(listener) async_hive.add(streamer) async_hive.run(threaded=True) stop.wait() assert len(listener.calls) > 0, 'Streamer did not yield any events' assert isinstance(listener.calls[0], pybeehive.Event), 'Streamer did not yield correct data'
def __init__(self): super(_EventWithResult, self).__init__() self._eventObj = _Event() self._eventObj.clear() self._results = []
def multithreadingTake(lockObj): def sendEvent(eventLst, who): eventLst[who].set() while eventLst[who].isSet(): # wait to the thread to work _sleep(1) testName = "Lock take test" _printHeader("%s for %s" % (testName, lockObj)) joinerEvent = _Event() joinerEvent.clear() userThreads = [] requestEvents = [] accessEvents = [] releaseEvents = [] printLock = _Lock() for i in range(2): requestEvent = _Event() accessEvent = _Event() releaseEvent = _Event() userThread = _Thread(target=threadFunction, args=(lockObj, joinerEvent, requestEvent, accessEvent, releaseEvent, printLock), name='%d' % (i)) requestEvents.append(requestEvent) accessEvents.append(accessEvent) releaseEvents.append(releaseEvent) userThreads.append(userThread) userThread.start() # here is where the test starts --- try: _printInfo("Initial state %r\n" % (lockObj), level=1, lock=printLock) if lockObj.isLock(): return False, "%s FAILED" % (testName) _printInfo("Tell the threads to access", level=1, lock=printLock, top=True) sendEvent(accessEvents, 0) sendEvent(accessEvents, 1) _printInfo("both should have had access", level=1, lock=printLock, bottom=True) _printInfo("Thread 0 take the lock", level=1, lock=printLock, top=True) sendEvent(requestEvents, 0) if not lockObj.isLock() or lockObj.owner != '0': raise Exception("It shall be lock by 0") _printInfo("Tell the threads to access", level=1, lock=printLock) sendEvent(accessEvents, 0) sendEvent(accessEvents, 1) _printInfo("0 should, but 1 don't", level=1, lock=printLock, bottom=True) _printInfo("Try to lock when it is already", level=1, lock=printLock, top=True) sendEvent(requestEvents, 1) if not lockObj.isLock() or lockObj.owner != '0': raise Exception("It shall be lock by user 0") _printInfo("Tell the threads to access", level=1, lock=printLock) sendEvent(accessEvents, 0) sendEvent(accessEvents, 1) _printInfo("0 should, but 1 don't", level=1, lock=printLock, bottom=True) _printInfo("Try to release by a NON-owner", level=1, lock=printLock, top=True) sendEvent(releaseEvents, 1) if not lockObj.isLock() or lockObj.owner != '0': raise Exception("It shall be lock by user 0") _printInfo("Tell the threads to access", level=1, lock=printLock) sendEvent(accessEvents, 0) sendEvent(accessEvents, 1) _printInfo("0 should, but 1 don't", level=1, lock=printLock, bottom=True) _printInfo("release the lock", level=1, lock=printLock, top=True) sendEvent(releaseEvents, 0) if lockObj.isLock(): raise Exception("It shall be released") _printInfo("Tell the threads to access", level=1, lock=printLock) sendEvent(accessEvents, 0) sendEvent(accessEvents, 1) _printInfo("both should have had to", level=1, lock=printLock, bottom=True) # TODO: timeout _printInfo("Thread 1 take the lock and expire it", level=1, lock=printLock, top=True) sendEvent(requestEvents, 1) if not lockObj.isLock() or lockObj.owner != '1': raise Exception("It shall be lock by 1") _printInfo("Tell the threads to access", level=1, lock=printLock) sendEvent(accessEvents, 0) sendEvent(accessEvents, 1) _printInfo("1 should, but 0 don't", level=1, lock=printLock) _printInfo("Sleep %d seconds to expire the lock" % TEST_EXPIRATION_TIME, level=1, lock=printLock) _sleep(TEST_EXPIRATION_TIME) _printInfo("Tell the threads to access", level=1, lock=printLock) sendEvent(accessEvents, 0) sendEvent(accessEvents, 1) _printInfo("both should have had to", level=1, lock=printLock, bottom=True) answer = True, "%s PASSED" % (testName) except Exception as e: print(e) print_exc() answer = False, "%s FAILED" % (testName) joinerEvent.set() while len(userThreads) > 0: userThread = userThreads.pop() userThread.join(1) if userThread.isAlive(): userThreads.append(userThread) print("All threads has finished") return answer
event.wait() #默认没有被set时 wait会一直等待 event.clear() #清空被设置的set 恢复默认的false print 'p 有人来买包子了' print 'p 开始为人做包子' time.sleep(5) #event.set() print 'p 包子做好了' event.set() #写在这里比上面更好一些,上面更能理解c 在wait def consumer(): print 'c 去买包子。。。' event.set() #将默认的事件flag设为True 原来是false 开始阻塞 time.sleep(2) print 'c 等包子做好' #print event.isSet() #判断是否set 是的话直接不等了 输出下面内容 类似异步 select while True: if event.isSet(): print '准备去拿 thanks...' else: print '还尼玛没好啊。。。' time.sleep(1) #print event.wait() # 效果= event.wait() #print 'c 准备去拿 thanks' event = threading._Event() p = threading.Thread(target=producer) c = threading.Thread(target=consumer) p.start() c.start()
def __init__(self, filters=None): super(TestListener, self).__init__(filters=filters) self.calls = [] self.closed = False self.setup_event = _Event() self.teardown_event = _Event()
def multithreading_take(lock_obj): def send_event(event_lst, who): event_lst[who].set() while event_lst[who].isSet(): # wait to the thread to work _sleep(1) test_name = "Lock take test" _print_header("{} for {}".format(test_name, lock_obj)) joiner_event = _Event() joiner_event.clear() user_threads = [] request_events = [] access_events = [] release_events = [] print_lock = _Lock() for i in range(2): request_event = _Event() access_event = _Event() release_event = _Event() user_thread = _Thread(target=thread_function, args=(lock_obj, joiner_event, request_event, access_event, release_event, print_lock), name='{:d}'.format(i)) request_events.append(request_event) access_events.append(access_event) release_events.append(release_event) user_threads.append(user_thread) user_thread.start() # here is where the test starts --- try: _print_info("Initial state {!r}\n".format(lock_obj), level=1, lock=print_lock) if lock_obj.isLock(): return False, "{} FAILED".format(test_name) _print_info("Tell the threads to access", level=1, lock=print_lock, top=True) send_event(access_events, 0) send_event(access_events, 1) _print_info("both should have had access", level=1, lock=print_lock, bottom=True) _print_info("Thread 0 take the lock", level=1, lock=print_lock, top=True) send_event(request_events, 0) if not lock_obj.isLock() or lock_obj.owner != '0': raise Exception("It shall be lock by 0") _print_info("Tell the threads to access", level=1, lock=print_lock) send_event(access_events, 0) send_event(access_events, 1) _print_info("0 should, but 1 don't", level=1, lock=print_lock, bottom=True) _print_info("Try to lock when it is already", level=1, lock=print_lock, top=True) send_event(request_events, 1) if not lock_obj.isLock() or lock_obj.owner != '0': raise Exception("It shall be lock by user 0") _print_info("Tell the threads to access", level=1, lock=print_lock) send_event(access_events, 0) send_event(access_events, 1) _print_info("0 should, but 1 don't", level=1, lock=print_lock, bottom=True) _print_info("Try to release by a NON-owner", level=1, lock=print_lock, top=True) send_event(release_events, 1) if not lock_obj.isLock() or lock_obj.owner != '0': raise Exception("It shall be lock by user 0") _print_info("Tell the threads to access", level=1, lock=print_lock) send_event(access_events, 0) send_event(access_events, 1) _print_info("0 should, but 1 don't", level=1, lock=print_lock, bottom=True) _print_info("release the lock", level=1, lock=print_lock, top=True) send_event(release_events, 0) if lock_obj.isLock(): raise Exception("It shall be released") _print_info("Tell the threads to access", level=1, lock=print_lock) send_event(access_events, 0) send_event(access_events, 1) _print_info("both should have had to", level=1, lock=print_lock, bottom=True) # TODO: timeout _print_info("Thread 1 take the lock and expire it", level=1, lock=print_lock, top=True) send_event(request_events, 1) if not lock_obj.isLock() or lock_obj.owner != '1': raise Exception("It shall be lock by 1") _print_info("Tell the threads to access", level=1, lock=print_lock) send_event(access_events, 0) send_event(access_events, 1) _print_info("1 should, but 0 don't", level=1, lock=print_lock) _print_info("Sleep {:d} seconds to expire the lock".format( TEST_EXPIRATION_TIME), level=1, lock=print_lock) _sleep(TEST_EXPIRATION_TIME) _print_info("Tell the threads to access", level=1, lock=print_lock) send_event(access_events, 0) send_event(access_events, 1) _print_info("both should have had to", level=1, lock=print_lock, bottom=True) answer = True, "{} PASSED".format(test_name) except Exception as e: print(e) print_exc() answer = False, "{} FAILED".format(test_name) joiner_event.set() while len(user_threads) > 0: user_thread = user_threads.pop() user_thread.join(1) if user_thread.is_alive(): user_threads.append(user_thread) print("All threads has finished") return answer
def __init__(self): self._event = _Event()
def __init__(self): self.event = threading._Event()
def __init__(self, topic=None): super(TestStreamer, self).__init__(topic=topic) self.count = 0 self.ex = False self.setup_event = _Event() self.teardown_event = _Event()
'encoding': 'utf-8', 'okcode': [0], 'prefix': 'auto', 'raise': True, 'sep': ' ', 'shell': False, 'sub': False, 'timeout': 0 }) CMDY_CONFIG = _Config() CMDY_CONFIG._load(dict(default=_CMDY_DEFAULT_CONFIG), '~/.cmdy.toml', './.cmdy.toml', 'CMDY.osenv') _CMDY_BAKED_ARGS = _Diot() _CMDY_EVENT = _Event() # The actions that will put left side on hold # For example: cmdy.ls().h() # will put cmdy.ls() on hold _CMDY_HOLDING_LEFT = ['a', 'async_', 'h', 'hold'] # The actions that will put right side on hold # For example: cmdy.ls().r(STDERR).fg() > DEVNULL # If "r" is in _CMDY_HOLDING_RIGHT, then fg() will be on hold # The command will run by ">" _CMDY_HOLDING_RIGHT = [] _CMDY_HOLDING_FINALS = [] _CMDY_RESULT_FINALS = [] class Cmdy:
def __init__(self, event, resume_at): _Thread.__init__(self, name="Timeout thread expiring at %s" % resume_at) self.event = event self.resume_at = resume_at self.cancel_event = _Event()