def call_later(fn, args=(), delay=0.001): """ Calls the provided function in a new thread after waiting some time. Useful for giving the system some time to process an event, without blocking the current execution flow. """ _Thread(target=lambda: _time.sleep(delay) or fn(*args)).start()
def calc_correction(self, _): """Calculate correction.""" if self._thread and self._thread.is_alive(): msg = 'ERR: Loop is Closed or MeasRespMat is On.' self._update_log(msg) _log.error(msg[5:]) return False _Thread(target=self._calc_correction, daemon=True).start() return True
def set_delta_kick(self, code, dkicks): """Calculate correction.""" if self._thread and self._thread.is_alive(): msg = 'ERR: Loop is Closed or MeasRespMat is On.' self._update_log(msg) _log.error(msg[5:]) return False _Thread( target=self._set_delta_kick, kwargs={'code': code, 'dkicks': dkicks}, daemon=True).start() return True
def calc_kicks(self, orbit): """Calculate the kick from the orbit distortion given.""" if orbit.size != self.inv_respmat.shape[1]: msg = 'ERR: Orbit and matrix size not compatible.' self._update_log(msg) _log.error(msg[5:]) return None kicks = _np.dot(self.inv_respmat, orbit) kicks *= -1 _Thread( target=self._update_dkicks, args=(kicks, ), daemon=True).start() # self._update_dkicks(kicks) return kicks
def start(self, run_callback, stop_callback, time_interval=TimeInterval.five_min, update_seconds=15): self._check_start_args(run_callback, stop_callback, time_interval, update_seconds) self._run_callback = run_callback self._stop_callback = stop_callback self._interval_seconds = int(time_interval.val) self._update_seconds = int(update_seconds) self._rflag = True try: self._thread = _Thread( target=self._update, daemon=True ) except: self._thread = _Thread( target=self._update ) self._thread.start()
def __init__(self, url, login, password): self._conn = url self._password = password self._login = login self._ws = websocket.WebSocketApp(self._conn, on_close=self._on_close, on_open=self._on_socket_open, on_message=self._on_message, on_error=self._on_error) self._t = _Thread(target=self._ws.run_forever) self._t.daemon = True self._thread_for_ping = _Thread(target=self.__quik_run_forever) self._thread_for_ping.daemon = True
def _init_threads(self): fmt = ' - {:<20s} ({:^20s}) [{:09.3f}] ms' t0_ = _time.time() # define process thread self._thread_process = _Thread(target=self._loop_process, daemon=True) # define scan thread self._dev_idx_last_scanned = \ len(self._device_ids)-1 # the next will be the first bsmp dev self._thread_scan = _Thread(target=self._loop_scan, daemon=True) dt_ = _time.time() - t0_ print(fmt.format('init_threads', 'create structures', 1e3 * dt_))
def _on_value_dead(self, ref): """ Function passed to the underlying weakref.ref object to be called when it's collected. It spawns a thread (to avoid locking up whatever thread garbage collection is happening on) that notifies all of this TWeakRef's retry events and then runs self._callback in a transaction. """ def run(): with _global_lock: for e in self._events: e.set() if self._callback is not None: atomically(self._callback) _Thread(name="%r dead value notifier" % self, target=run).start()
def set_auto_corr(self, value): """.""" if value == self._csorb.LoopState.Closed: if self._loop_state == self._csorb.LoopState.Closed: msg = 'ERR: Loop is Already closed.' self._update_log(msg) _log.error(msg[5:]) return False if self._thread and self._thread.is_alive(): msg = 'ERR: Cannot Correct, Measuring RespMat.' self._update_log(msg) _log.error(msg[5:]) return False if not self.havebeam: msg = 'ERR: Cannot Correct, We do not have stored beam!' self._update_log(msg) _log.error(msg[5:]) return False msg = 'Closing the Loop.' self._update_log(msg) _log.info(msg) self._loop_state = value self._thread = _Thread( target=self._do_auto_corr, daemon=True) self._thread.start() elif value == self._csorb.LoopState.Open: msg = 'Opening the Loop.' self._update_log(msg) _log.info(msg) self._loop_state = value return True
def _start_meas_respmat(self): if self.orbit.mode == self._csorb.SOFBMode.Offline: msg = 'ERR: Cannot Meas Respmat in Offline Mode' self._update_log(msg) _log.error(msg[5:]) return False if self._measuring_respmat: msg = 'ERR: Measurement already in process.' self._update_log(msg) _log.error(msg[5:]) return False if self._thread and self._thread.is_alive(): msg = 'ERR: Cannot Measure, Loop is Closed.' self._update_log(msg) _log.error(msg[5:]) return False if not self.havebeam: msg = 'ERR: Cannot Measure, We do not have stored beam!' self._update_log(msg) _log.error(msg[5:]) return False msg = 'Starting RespMat measurement.' self._update_log(msg) _log.info(msg) self._measuring_respmat = True self._thread = _Thread(target=self._do_meas_respmat, daemon=True) self._thread.start() return True
def _start_meas_config(self): """Start configuration measurement.""" cont = True if self._sync_corr == _Const.SyncCorr.On: log_msg = 'ERR: Turn off syncronized correction!' cont = False elif self._meas_config_name == 'UNDEF': log_msg = 'ERR: Define a conf.name to save the measure!' cont = False elif self._status != 0: log_msg = 'ERR: Verify power supplies status!' cont = False elif self._measuring_config: log_msg = 'ERR: Measurement already in progress!' cont = False elif not self._is_storedebeam: log_msg = 'ERR: Cannot measure, there is not stored beam!' cont = False elif not self._tune_x_pv.connected or not self._tune_y_pv.connected: log_msg = 'ERR: Cannot measure, tune PVs not connected!' cont = False if not cont: self.run_callbacks('Log-Mon', log_msg) return False self.run_callbacks( 'Log-Mon', 'Starting correction config measurement!') self._measuring_config = True thread = _Thread(target=self._meas_config_thread, daemon=True) thread.start() return True
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 _start_request_in_new_thread(self, function, *args, **kwargs): if self._use_processes is True: t = Process(target=self.__do_request, args=(function,)+args, kwargs=kwargs) else: t = _Thread(target=self.__do_request, args=(function,)+args, kwargs=kwargs) t.daemon = True t.start()
def __init__(self, name, job=None): """Class initialization. *name* is the name of the player. *job* is a DGProfession instance Note: *name* must be changed to Player object when implemented in DetectiveGame420 java plugin. """ self._name = name self._job = job self._iskiller = False self._score = 0 self._sanitation = _randint(SANITATION_LOWEST_INITVALUE, 99) self._soaked = False self._invisible = False self._breath = 0 self._bloody = False self._alive = True # this variable must have no other means of setting its value to False self._bloody_once = False # sanitation drop start self.__sanitation_fall_thread = _Thread(target=self.__fsanitation) self.__sanitation_fall_thread.setDaemon(True) self.__sanitation_fall_thread.start() self.__initialized = True
def __init__(self, fn, args=[], kwargs={}, delay=0.5, msg=None, callback=None): '''Creates a new Alert. Args: fn: Callable to monitor for changes. args: Positional args when checking the callable. kwargs: Keyword args when checking the callable. delay: Frequency to check for changes, in seconds. msg: Notification string to display on change. callback: Callback function to call upon change. It must accept two arguments: initial value, new value ''' if not callable(fn): raise TypeError("You can only set an alert on a callable object") self._kill = False self._thread = _Thread(target=self._loop, daemon=True, args=(fn, args, kwargs, delay, msg, callback)) self._thread.start() _instances.add(self)
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 process(self): """Process operation from queue.""" # first check if a thread is already running with self._lock: donothing = not self._enabled donothing |= self._thread is not None and self._thread.is_alive() if donothing: return False # no thread is running, we can process queue try: operation = super().popleft() except IndexError: # there is nothing in the queue return False # process operation taken from queue args, kws = tuple(), dict() if len(operation) == 1: func = operation[0] elif len(operation) == 2: func, args = operation elif len(operation) >= 3: func, args, kws = operation[:3] self._thread = _Thread(target=func, args=args, kwargs=kws, daemon=True) self._thread.start() return True
def _run(self, fn, running): thread = _Thread(target=fn) thread.start() try: while running.value: try: self.flush() if self.child.poll(POLL_INTERVAL): event = self.child.recv() channel = event.channel target = event.target self.send(event, channel, target) except SystemExit: running.acquire() running.value = False running.release() break except KeyboardInterrupt: running.acquire() running.value = False running.release() break finally: running.acquire() running.value = False running.release() thread.join() self.flush()
def get_index_blocks(locs, info, size, callback=None): locs = _lib.ensure_sanity(locs, info) # Sort locs by indices x_index = _np.uint32(locs.x / size) y_index = _np.uint32(locs.y / size) sort_indices = _np.lexsort([x_index, y_index]) locs = locs[sort_indices] x_index = x_index[sort_indices] y_index = y_index[sort_indices] # Allocate block info arrays n_blocks_y, n_blocks_x = index_blocks_shape(info, size) block_starts = _np.zeros((n_blocks_y, n_blocks_x), dtype=_np.uint32) block_ends = _np.zeros((n_blocks_y, n_blocks_x), dtype=_np.uint32) K, L = block_starts.shape # Fill in block starts and ends # We are running this in a thread with a nogil numba function. This helps updating a potential GUI with the callback. if callback is not None: callback(0) counter = [0] else: counter = None thread = _Thread(target=_fill_index_blocks, args=(block_starts, block_ends, x_index, y_index, counter)) thread.start() if callback is not None: while counter[0] < K: callback(counter[0]) _time.sleep(0.1) thread.join() if callback is not None: callback(counter[0]) return locs, size, x_index, y_index, block_starts, block_ends, K, L
def __init__(self, block, interval_obj, interval_sec, poll_sec=1, interval_cb=None, time_func=time.localtime): self._rflag = False self._check_params(interval_obj, interval_sec, poll_sec, interval_cb, time_func) self._iobj = interval_obj self._isec = interval_sec self._psec = round(interval_sec / round(interval_sec / poll_sec), 5) self._min_block_size = self.BLOCK_SIZE_PER_PSEC * poll_sec self._check_block(block) self._block = block self._texcludes = set() self._ssfunc = block.stream_snapshot_from_marker self._restrict_block_resize(block, poll_sec) self._tfunc = time_func self._interval_cb = interval_cb self._wait_adj_down_exp = 0 self._buffers = dict() self._buffers_lock = _Lock() self._bthread = _Thread(target=self._background_worker) self._bthread.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 mouse_handler(callback=None): """ :returns an input thread Call mouse_handler.start() in order to start listening """ if callback is None: def callback(): pass def on_move(x, y): mouse["pos"] = (x, y) callback() def on_click(x, y, button, pressed): mouse[ButtonCode.code_of(button)] = pressed callback() def on_scroll(x, y, dx, dy): mouse["HScroll"] = dx mouse["VScroll"] = dy callback() # Collect events until released def get_input(): with _mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: listener.join() return _Thread(target=get_input, name="Mouse-Thread", daemon=True)
def __init__(self, target, arginLst, parallel=None, checkPeriod=None, preHook=None, preExtraArgs=None, postHook=None, postExtraArgs=None, *args, **kwargs): """ Build an object with the capacity to execute multiple process with the same method. It will build a pool of processes where they will take elements in a shared queue until the queue is empty. Arguments: - target: Method that each of the parallel process will be executing with the input arguments. It must be callable with objects in the list as parameters. - arginLst: python list where each element is data input for the method that will be executed in parallel. - parallel: (optional) to establish the number of parallel processes that will participate. By default the maximum possible based on the number of cores available. """ super(Pool, self).__init__(*args, **kwargs) # prepare the parameters --- self.__target = target self.__checkPeriod = 60 # seconds self.__parallel = None self.__workersLst = [] self.__input = _Queue() self.__inputNelements = 0 self.__output = _Queue() self.__poolMonitor = _Thread(target=self.__poolMonitorThread) self.__poolMonitor.setDaemon(True) self.__collected = [] self.__loadAverage = _LoadAverage(*args, **kwargs) self._instances.append(self.__loadAverage) self.__memoryPercent = _MemoryPercent(*args, **kwargs) self._instances.append(self.__memoryPercent) self.__events = _EventManager() self.__events.loggingFolder = self.loggingFolder self.__events.loggerName = self.loggerName self.__events.logLevel = self.logLevel self.__events.logEnable = self.logEnable self._instances.append(self.__events) # hooks --- self.__preHook = preHook self.__preExtraArgs = preExtraArgs self.__postHook = postHook self.__postExtraArgs = postExtraArgs # setup --- self.__prepareParallel(parallel) self.__prepareInputQueue(arginLst) self.__prepareWorkers(*args, **kwargs) self.__prepareMonitoring() self.debug("Prepared a yamp.Pool() version %s" % (_version()))
def start(self, run_callback, stop_callback, time_interval=TimeInterval.five_min, update_seconds=15): self._check_start_args(run_callback, stop_callback, time_interval, update_seconds) self._run_callback = run_callback self._stop_callback = stop_callback self._interval_seconds = int(time_interval.val) self._update_seconds = int(update_seconds) self._rflag = True try: self._thread = _Thread(target=self._update, daemon=True) except: self._thread = _Thread(target=self._update) self._thread.start()
def _on_value_dead(self, ref): """ Function passed to the underlying weakref.ref object to be called when it's collected. It spawns a thread (to avoid locking up whatever thread garbage collection is happening on) that notifies all of this TWeakRef's retry queues and then runs self._callback in a transaction. """ def run(): with _global_lock: for q in self._queues: try: q.put(None, False) except Full: pass if self._callback is not None: atomically(self._callback) _Thread(name="%r dead value notifier" % self, target=run).start()
def start(self): """ Start the daemon """ self.thread = _Thread(target=self.listenForRequests) self.hastofinish = False self.thread.start()
def threaded(*args, **kwargs) -> _Thread: thread = _Thread( target=queue_awaiter, args=(wrapped_func, *args), kwargs=kwargs, daemon=True, ) thread.start() return thread
def __init__(self, *queues: _Queue, multicasted_queue: _Queue = _Queue()): self.__multicast_queue = multicasted_queue self._output_queues = queues self.is_stopped = False self._thread = _Thread( target=self._publisher_multicast, args=(self.__multicast_queue, *self._output_queues), daemon=True, ) self._thread.start()
def __init__(self, id, target, inputQueue, outputQueue, checkPeriod=None, preHook=None, preExtraArgs=None, postHook=None, postExtraArgs=None, *args, **kwargs): """ Build an object... Arguments: + id: integer that can identify the worker between others. + target: Method that each of the parallel process will be executing with the input arguments. It must be callable with objects in the argin queue as parameters. + inputQueue: multithreading queue where each element is data input for the method that will be executed by the child process. + outputQueue: multithreading queue where the results will be stored after the execution. * {pre, post}Hook: callable objects to be executed before or after the target. * {pre, post}ExtraArgs: dictionaries that will be passed to hooks. """ super(Worker, self).__init__(*args, **kwargs) self.__id = id if not callable(target): raise AssertionError("Target must be callable object") else: self.__target = target self.__input = inputQueue self.__currentArgin = None self.__output = outputQueue self.__ctr = _Value(_ulonglong, 0) self.__computationTime = _Value(_float, 0.0) self.__currentArgout = None self.__checkPeriod = 60 # seconds self.checkPeriod = checkPeriod # Events --- self.__events = _EventManager() self.__prepared = _Event() self.__prepared.clear() self.__internalEvent = _Event() self.__internalEvent.clear() # Hooks --- self.__preHook = None self.__preExtraArgs = None self.__postHook = None self.__postExtraArgs = None self.preHook = preHook self.preExtraArgs = preExtraArgs self.postHook = postHook self.postExtraArgs = postExtraArgs # thread and process --- self.__monitor = _Thread(target=self.__thread) self.__worker = None self.__monitor.setDaemon(True) self.__monitor.start() self.__workerPausedFlag = False
def _setup_main_queue(self): self._queue = Queue() if self._use_processes is True: t = Process(target=self._process_queue) else: t = _Thread(target=self._process_queue) t.name = "Queue" t.daemon = True t.start() print "Queue started", t
def _spawn_thread(name, target): def _target(): try: target() except: _handle_exception(*_sys.exc_info()) t = _Thread(target = _target, name = name) t.daemon = False t.start() return t
def __init__(self, prefix, *args): """Create Computed PVs.""" super().__init__() self._prefix = prefix self._queue = _QueueThread() self.pvs = list() self.scanning = False self.quit = False self._create_computed_pvs(*args) self.thread = _Thread(target=self.scan, daemon=True) self.thread.start()
def __init__(self, time_to_wait: float, output_queue=_Queue()): if time_to_wait <= 0: raise TypeError("time_to_wait must be greater than zero") self._time_to_wait = time_to_wait self._is_finished = False self._stop_q: _Queue = _Queue() self._output_q = output_queue self._select = _Select(self._stop_q) self._timer_thread = _Thread( target=self._timer, args=(self._output_q, self._time_to_wait), daemon=True ) self._timer_thread.start()
def apply_corr(self, code): """Apply calculated kicks on the correctors.""" if self.orbit.mode == self._csorb.SOFBMode.Offline: msg = 'ERR: Offline, cannot apply kicks.' self._update_log(msg) _log.error(msg[5:]) return False if self._thread and self._thread.is_alive(): msg = 'ERR: Loop is Closed or MeasRespMat is On.' self._update_log(msg) _log.error(msg[5:]) return False if self._dtheta is None: msg = 'ERR: Cannot Apply Kick. Calc Corr first.' self._update_log(msg) _log.error(msg[5:]) return False _Thread( target=self._apply_corr, kwargs={'code': code}, daemon=True).start() return True
def reset(self, valmax=None, barsize=None, title=None, bar=None, up_every=None): """ Resets the progress bar with initialization values, unless new values are given Args: * valmax (float): the finish value of the progress bar. Default is 100. * barsize (int >0): the size of the bar in the opened terminal. If ``None``, the bar will automatically fit the width of the window. * title (str): the title, printed one line above the progress bar. * bar (bool): whether the bar should be displayed or not. If ``False``, only the text given at each :func:`update` will be printed. * up_every (int [0-100]): if ``bar`` is ``True``, the progress bar will be updated every ``up_every`` percent of progress. Setting ``up_every`` = 0 updates the progress bar at each :func:`update`. """ super(Patiencebarmulti, self).reset(valmax=valmax, barsize=barsize, title=title, bar=bar, up_every=up_every) self._running = True checker = _Thread(target=self._check) checker.setDaemon(True) checker.start()
def __init__(self, block, interval_obj, interval_sec, poll_sec=1, interval_cb=None, time_func=time.localtime): self._rflag = False self._check_params(interval_obj, interval_sec, poll_sec, interval_cb, time_func) self._iobj = interval_obj self._isec = interval_sec self._psec = round(interval_sec / round(interval_sec/poll_sec), 5) self._min_block_size = self.BLOCK_SIZE_PER_PSEC * poll_sec self._check_block(block) self._block = block self._texcludes = set() self._ssfunc = block.stream_snapshot_from_marker self._restrict_block_resize(block, poll_sec) self._tfunc = time_func self._interval_cb = interval_cb self._wait_adj_down_exp = 0 self._buffers = dict() self._buffers_lock = _Lock() self._bthread = _Thread(target=self._background_worker) self._bthread.start()
while True: task = _apply_queue.get() assert isinstance(task, tuple) # print ("task", *task) if task[0] == 'write': _, setting, value, sbox = task GLib.idle_add(_write_start, sbox, priority=0) value = setting.write(value) elif task[0] == 'read': _, setting, force_read, sbox = task value = setting.read(not force_read) GLib.idle_add(_update_setting_item, sbox, value, priority=99) from threading import Thread as _Thread _queue_processor = _Thread(name='SettingsProcessor', target=_process_apply_queue) _queue_processor.daemon = True _queue_processor.start() # # # def _switch_notify(switch, _, setting, spinner): # print ("switch notify", switch, switch.get_active(), setting) if switch.get_sensitive(): # value = setting.write(switch.get_active() == True) # _update_setting_item(switch.get_parent(), value) _apply_queue.put(('write', setting, switch.get_active() == True, switch.get_parent()))
def _request_async(self): th = _Thread(target=self._request) th.start()
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
def __init__(self, *args, **kwargs): super(Thread, self).__init__(*args, **kwargs) self._running = False self._thread = _Thread(target=self.run)