本文整理汇总了Python中threading.Event.set方法的典型用法代码示例。如果您正苦于以下问题:Python Event.set方法的具体用法?Python Event.set怎么用?Python Event.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Event
的用法示例。
在下文中一共展示了Event.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_closes_if_not_hit
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
def test_closes_if_not_hit():
try:
da = DummyHandler()
fa = Event()
sa = RawServer(fa, 2, 2)
loop(sa)
sl(sa, da, beginport + 14)
sleep(1)
db = DummyHandler()
fb = Event()
sb = RawServer(fb, 100, 100)
loop(sb)
sl(sb, db, beginport + 13)
sleep(.5)
sa.start_connection(('127.0.0.1', beginport + 13))
sleep(1)
assert da.external_made == []
assert da.data_in == []
assert da.lost == []
assert len(db.external_made) == 1
del db.external_made[:]
assert db.data_in == []
assert db.lost == []
sleep(3.1)
assert len(da.lost) == 1
assert len(db.lost) == 1
finally:
fa.set()
fb.set()
示例2: StoppableQThread
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class StoppableQThread(QtCore.QThread):
""" Base class for QThreads which require the ability
to be stopped by a thread-safe method call
"""
def __init__(self, parent=None):
self._should_stop = Event()
self._should_stop.clear()
super(StoppableQThread, self).__init__(parent)
def join(self, timeout=0):
""" Joins the current thread and forces it to stop after
the timeout if necessary
:param timeout: Timeout duration in seconds
"""
self._should_stop.wait(timeout)
if not self.should_stop():
self.stop()
super(StoppableQThread, self).wait()
def stop(self):
self._should_stop.set()
def should_stop(self):
return self._should_stop.is_set()
def __repr__(self):
return "<%s(should_stop=%s)>" % (self.__class__.__name__, self.should_stop())
示例3: ResponseWaiter
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class ResponseWaiter(object):
def __init__(self, connection, num_responses):
self.connection = connection
self.pending = num_responses
self.error = None
self.responses = [None] * num_responses
self.event = Event()
def got_response(self, response, index):
with self.connection.lock:
self.connection.in_flight -= 1
if isinstance(response, Exception):
self.error = response
self.event.set()
else:
self.responses[index] = response
self.pending -= 1
if not self.pending:
self.event.set()
def deliver(self, timeout=None):
self.event.wait(timeout)
if self.error:
raise self.error
elif not self.event.is_set():
raise OperationTimedOut()
else:
return self.responses
示例4: __init__
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class ResponseEvent:
"""Event which is fired when the response is returned for a request.
For each request sent this event is created.
An application can wait for the event to create a blocking request.
"""
def __init__(self):
self.__evt = Event()
def waiting(self):
return not self.__evt.isSet()
def waitForResponse(self, timeOut=None):
"""blocks until the response arrived or timeout is reached."""
self.__evt.wait(timeOut)
if self.waiting():
raise Timeout()
else:
if self.response["error"]:
raise Exception(self.response["error"])
else:
return self.response["result"]
def handleResponse(self, resp):
self.response = resp
self.__evt.set()
示例5: test_ask_shutdown
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
def test_ask_shutdown(self):
q = queue.Queue()
done = Event()
done.set()
channel = controller.Channel(q, done)
with tutils.raises(Kill):
channel.ask("test", Mock(name="test_ask_shutdown"))
示例6: ThreadedRunner
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class ThreadedRunner(Runnable):
def __init__(self, runnable):
self._runnable = runnable
self._notifier = Event()
self._result = None
self._error = None
self._traceback = None
self._thread = None
def run(self):
try:
self._result = self._runnable()
except:
self._error, self._traceback = sys.exc_info()[1:]
self._notifier.set()
__call__ = run
def run_in_thread(self, timeout):
self._thread = Thread(self, name=TIMEOUT_THREAD_NAME)
self._thread.setDaemon(True)
self._thread.start()
self._notifier.wait(timeout)
return self._notifier.isSet()
def get_result(self):
if self._error:
raise self._error, None, self._traceback
return self._result
def stop_thread(self):
self._thread.stop()
示例7: Queue
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class Queue(list):
def __init__(self):
super(Queue, self).__init__()
self._lock = Lock()
self._fill = Event()
def put(self, obj):
with self._lock:
self.append(obj)
self._fill.set()
def get(self, block=True):
with self._lock:
if len(self) == 0:
self._fill.clear()
if not self._fill.isSet():
if block:
self._fill.wait()
else:
return None
with self._lock:
return self.pop(0)
def delete(self, index):
if 0 <= index < len(self):
with self._lock:
del self[index]
def remove(self, element):
if element in self:
with self._lock:
del self[self.index(element)]
示例8: test_concurrent_rendering
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
def test_concurrent_rendering():
'''Best-effort testing that concurrent multi-threaded rendering works.
The test has no guarantees around being deterministic, but if it fails
you know something is wrong with concurrent rendering. If it passes,
things are probably working.'''
err = None
def func(sim, event):
event.wait()
sim.data.qpos[:] = 0.0
sim.forward()
img1 = sim.render(width=40, height=40, camera_name="camera1")
img2 = sim.render(width=40, height=40, camera_name="camera2")
try:
assert np.sum(img1[:]) == 23255
assert np.sum(img2[:]) == 12007
except Exception as e:
nonlocal err
err = e
model = load_model_from_xml(BASIC_MODEL_XML)
sim = MjSim(model)
sim.render(100, 100)
event = Event()
threads = []
for _ in range(100):
thread = Thread(target=func, args=(sim, event))
threads.append(thread)
thread.start()
event.set()
for thread in threads:
thread.join()
assert err is None, "Exception: %s" % (str(err))
示例9: TestInterruptible
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class TestInterruptible(unittest.TestCase):
""" Tests for interrupting cooperative threads """
def test_interruptible_decorator(self):
""" Tests for the @interruptible decorator. """
self.quit_condition = False
cancellation_point = lambda: _cancellation_point(
lambda: self.quit_condition)
self.thread_started = Event()
@interruptible
def never_ending(cancellation_point):
self.thread_started.set()
while True:
time.sleep(0.1)
cancellation_point()
thread = Thread(target=never_ending, args=(cancellation_point, ))
thread.start()
self.thread_started.wait()
self.quit_condition = True
countdown = 10
while thread.is_alive() and countdown > 0:
time.sleep(0.1)
countdown -= 1
self.assertFalse(thread.is_alive())
示例10: GarbageCollectorThread
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class GarbageCollectorThread(Thread):
"""Thread in which garbage collection actually happens."""
def __init__(self, gc):
super(GarbageCollectorThread, self).__init__()
self.gc = gc
self.daemon = True
self.pid = getpid()
self.ready = Event()
def run(self):
s = self.gc.context.socket(zmq.PULL)
s.linger = 0
s.bind(self.gc.url)
self.ready.set()
while True:
# detect fork
if getpid is None or getpid() != self.pid:
return
msg = s.recv()
if msg == b'DIE':
break
fmt = 'L' if len(msg) == 4 else 'Q'
key = struct.unpack(fmt, msg)[0]
tup = self.gc.refs.pop(key, None)
if tup and tup.event:
tup.event.set()
del tup
s.close()
示例11: request_token_spotty
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
def request_token_spotty(spotty, use_creds=True):
'''request token by using the spotty binary'''
token_info = None
if spotty.playback_supported:
try:
args = ["-t", "--client-id", CLIENTID, "--scope", ",".join(SCOPE), "-n", "temp-spotty"]
done = Event()
spotty = spotty.run_spotty(arguments=args, use_creds=use_creds)
watcher = Thread(target=kill_on_timeout, args=(done, 5, spotty))
watcher.daemon = True
watcher.start()
stdout, stderr = spotty.communicate()
done.set()
result = None
log_msg("request_token_spotty stdout: %s" % stdout)
for line in stdout.split():
line = line.strip()
if line.startswith("{\"accessToken\""):
result = json.loads(line)
# transform token info to spotipy compatible format
if result:
token_info = {}
token_info["access_token"] = result["accessToken"]
token_info["expires_in"] = result["expiresIn"]
token_info["token_type"] = result["tokenType"]
token_info["scope"] = ' '.join(result["scope"])
token_info['expires_at'] = int(time.time()) + token_info['expires_in']
token_info['refresh_token'] = result["accessToken"]
except Exception as exc:
log_exception(__name__, exc)
return token_info
示例12: TimerWithResume
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class TimerWithResume(object):
def __init__(self, status_subject, refresh_interval):
self.status_subject = status_subject
self.abort = Event()
self.refresh_interval = refresh_interval
def perform(self):
while not self.abort.isSet():
self.status_subject.build_status()
self.abort.wait(self.refresh_interval)
def stop(self):
self.abort.set()
def start(self):
self.thread = Thread(target=self.perform)
self.thread.daemon = True
self.thread.start()
def resume(self):
self.thread.join()
self.abort.clear()
self.start()
def set_refresh_interval(self, new_interval):
self.refresh_interval = new_interval
示例13: StoppableThreadWithResult
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class StoppableThreadWithResult(Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None):
super(StoppableThreadWithResult, self).__init__(group=group, target=target,
name=name, args=args, kwargs=kwargs, verbose=verbose)
self._stop = Event()
def stop(self):
self._stop.set()
self._Thread__stop()
def stopped(self):
return self._stop.isSet()
def run(self):
if self._Thread__target is not None:
self._return = self._Thread__target(*self._Thread__args,
**self._Thread__kwargs)
def join(self, timeout=None):
Thread.join(self, timeout=None)
return self._return
示例14: NonSubscribeListener
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class NonSubscribeListener(object):
def __init__(self):
self.result = None
self.status = None
self.done_event = Event()
def callback(self, result, status):
self.result = result
self.status = status
self.done_event.set()
def pn_await(self, timeout=5):
""" Returns False if a timeout happened, otherwise True"""
return self.done_event.wait(timeout)
def await_result(self, timeout=5):
self.pn_await(timeout)
return self.result
def await_result_and_reset(self, timeout=5):
self.pn_await(timeout)
cp = copy.copy(self.result)
self.reset()
return cp
def reset(self):
self.result = None
self.status = None
self.done_event.clear()
示例15: Task
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import set [as 别名]
class Task(object):
def __init__(self, name, start_time, calc_next_time, func):
"""
Initialize a Task.
Arguments:
name - Name of task.
start_time - First time for task to run
calc_next_time - Function to calculate the time of next run,
gets one argument, the last run time as a datetime.
Returns None when task should no longer be run
func - A function to run
"""
self.name = name
self.start_time = start_time
self.scheduled_time = start_time
self.calc_next_time = calc_next_time
self.func = func
self.halt_flag = Event()
def run(self):
logging.debug("Running %s task, scheduled at: %s" % (self.name, self.scheduled_time,))
if not self.halt_flag.isSet():
try:
try:
self.func()
except:
raise
finally:
self.scheduled_time = self.calc_next_time(self.scheduled_time)
logging.debug("Scheduled next run of %s for: %s" % (self.name, self.scheduled_time,))
def halt(self):
self.halt_flag.set()