本文整理汇总了Python中threading.Condition.notify_all方法的典型用法代码示例。如果您正苦于以下问题:Python Condition.notify_all方法的具体用法?Python Condition.notify_all怎么用?Python Condition.notify_all使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Condition
的用法示例。
在下文中一共展示了Condition.notify_all方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MySubHandler
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class MySubHandler(opcua.SubscriptionHandler):
"""
More advanced subscription client using conditions, so we can wait for events in tests
"""
def setup(self):
self.cond = Condition()
self.node = None
self.handle = None
self.attribute = None
self.value = None
self.ev = None
return self.cond
def data_change(self, handle, node, val, attr):
self.handle = handle
self.node = node
self.value = val
self.attribute = attr
with self.cond:
self.cond.notify_all()
def event(self, handle, event):
self.ev = event
with self.cond:
self.cond.notify_all()
示例2: Event
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class Event(object):
def __init__(self,):
self.__cond = Condition(Lock())
self.__flag = False
def isSet(self):
return self.__flag
is_set = isSet
def set(self):
self.__cond.acquire()
try:
self.__flag = True
self.__cond.notify_all()
finally:
self.__cond.release()
def clear(self):
self.__cond.acquire()
try:
self.__flag = False
finally:
self.__cond.release()
def wait(self, timeout=None):
self.__cond.acquire()
try:
if not self.__flag:
self.__cond.wait(timeout)
return self.__flag
finally:
self.__cond.release()
示例3: KeepAlive
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class KeepAlive(Thread):
"""
Used by Client to keep session opened.
OPCUA defines timeout both for sessions and secure channel
"""
def __init__(self, client, timeout):
Thread.__init__(self)
self.logger = logging.getLogger(__name__)
if timeout == 0: # means no timeout bu we do not trust such servers
timeout = 360000
self.timeout = timeout
self.client = client
self._dostop = False
self._cond = Condition()
def run(self):
self.logger.debug("starting keepalive thread with period of %s milliseconds", self.timeout)
server_state = self.client.get_node(ua.FourByteNodeId(ua.ObjectIds.Server_ServerStatus_State))
while not self._dostop:
with self._cond:
self._cond.wait(self.timeout/1000)
if self._dostop:
break
self.logger.debug("renewing channel")
self.client.open_secure_channel(renew=True)
val = server_state.get_value()
self.logger.debug("server state is: %s ", val)
self.logger.debug("keepalive thread has stopped")
def stop(self):
self.logger.debug("stoping keepalive thread")
with self._cond:
self._cond.notify_all()
self._dostop = True
示例4: Node
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class Node(object):
STATE_INIT = 0
STATE_STARTING = 1
STATE_RUNNING = 2
STATE_STOPPED = 3
STATE_PARTITIONED = 4
STATE_FAILED = 5
state_str = {STATE_INIT: "Initial",
STATE_STARTING: "Starting",
STATE_RUNNING: "Running",
STATE_STOPPED: "Stopped",
STATE_FAILED: "Failed"}
def __init__(self, node_id):
self.node_id = node_id
self.state = Node.STATE_INIT
self.cv_lock = Lock()
self.cv = Condition(self.cv_lock)
def wait_for_state(self, state):
self.cv.acquire()
while self.state not in (state, Node.STATE_FAILED):
self.cv.wait()
self.cv.release()
if self.state != state:
raise ChistributedException("Node entered failed state while waiting for state %s" % Node.state_str[state])
def set_state(self, state):
self.cv.acquire()
self.state = state
self.cv.notify_all()
self.cv.release()
示例5: BinaryServer
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class BinaryServer(Thread):
"""
Socket server forwarding request to internal server
"""
def __init__(self, internal_server, hostname, port):
Thread.__init__(self)
self.socket_server = None
self.hostname = hostname
self.port = port
self.iserver = internal_server
self._cond = Condition()
def start(self):
with self._cond:
Thread.start(self)
self._cond.wait()
def run(self):
logger.warning("Listening on %s:%s", self.hostname, self.port)
socketserver.TCPServer.allow_reuse_address = True # get rid of address already in used warning
self.socket_server = ThreadingTCPServer((self.hostname, self.port), UAHandler)
# self.socket_server.daemon_threads = True # this will force a shutdown of all threads, maybe too hard
self.socket_server.internal_server = self.iserver # allow handler to acces server properties
with self._cond:
self._cond.notify_all()
self.socket_server.serve_forever()
def stop(self):
logger.warning("server shutdown request")
self.socket_server.shutdown()
示例6: __init__
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class MockSock:
def __init__(self):
self.sent = six.binary_type()
self.send_q = deque()
self.recv_q = deque()
self.closed = False
self.lock = Lock()
self.cond = Condition(self.lock)
self.timeout = 0.5
def gettimeout(self):
return self.timeout
def close(self):
self.lock.acquire()
self.closed = True
self.lock.release()
def queue_send(self, num_bytes):
self.lock.acquire()
try:
self.send_q.append(num_bytes)
self.cond.notify_all()
finally:
self.lock.release()
def send(self, message):
self.lock.acquire()
try:
while not len(self.send_q):
self.cond.wait()
num_bytes = self.send_q.popleft()
if num_bytes < len(message):
self.send_q.appendleft(len(message) - num_bytes)
sent = min(num_bytes, len(message))
self.sent += message[:sent]
return sent
finally:
self.lock.release()
def queue_recv(self, message):
self.lock.acquire()
try:
self.recv_q.append(message)
self.cond.notify_all()
finally:
self.lock.release()
def recv(self, max_len):
self.lock.acquire()
try:
while not len(self.recv_q):
self.cond.wait()
message = self.recv_q.popleft()
recd = min(max_len, len(message))
if (recd < len(message)):
self.recv_q.appendleft(message[recd:])
return message[:recd]
finally:
self.lock.release()
示例7: SendBuffer
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class SendBuffer(object):
def __init__(self, max_size):
self.size = 0
self.frontbuffer = ''
self.full = Condition()
self.backbuffer = StringIO()
self.max_size = max_size
def __len__(self):
return len(self.frontbuffer) + self.size
def write(self, data):
dlen = len(data)
with self.full:
while self.size + dlen > self.max_size and dlen < self.max_size:
# if a single write is bigger than the buffer, swallow hard.
# No amount of waitng will make it fit.
self.full.wait()
self.backbuffer.write(data)
self.size += dlen
def to_sock(self, sock):
if not self.frontbuffer:
with self.full:
buf, self.backbuffer = self.backbuffer, StringIO()
self.size = 0
self.full.notify_all()
self.frontbuffer = buf.getvalue()
written = sock.send(self.frontbuffer)
self.frontbuffer = self.frontbuffer[written:]
示例8: ThreadLoop
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class ThreadLoop(Thread):
def __init__(self):
Thread.__init__(self)
self.logger = logging.getLogger(__name__)
self.loop = None
self._cond = Condition()
def start(self):
with self._cond:
Thread.start(self)
self._cond.wait()
def run(self):
self.logger.debug("Starting subscription thread")
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
with self._cond:
self._cond.notify_all()
self.loop.run_forever()
self.logger.debug("subscription thread ended")
def stop(self):
"""
stop subscription loop, thus the subscription thread
"""
self.loop.call_soon_threadsafe(self.loop.stop)
def call_soon(self, callback):
self.loop.call_soon_threadsafe(callback)
def call_later(self, delay, callback):
p = functools.partial(self.loop.call_later, delay, callback)
self.loop.call_soon_threadsafe(p)
示例9: __init__
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class Barrier:
def __init__(self, num_threads):
self.num_threads = num_threads
self.count = num_threads
self.iter = 0
self.cond = Condition()
def wait(self):
self.cond.acquire()
i = self.iter
self.count -= 1
if self.count == 0:
self.iter += 1
self.count = self.num_threads
self.cond.notify_all()
self.cond.release()
return True
# Release lock and block this thread until notified/woken.
# Allow for spurious wake-ups.
while 1:
self.cond.wait(None)
if i != self.iter:
break
self.cond.release()
return False
示例10: LockedDirectories
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class LockedDirectories(object):
"""
Class that keeps a list of locked directories
"""
def __init__(self):
self.dirs = set()
self.cv = Condition()
def run_in(self, dir_):
"""
Start running in the directory and lock it
"""
self.cv.acquire()
while dir_ in self.dirs:
self.cv.wait()
self.dirs.add(dir_)
self.cv.release()
def done(self, dir_):
"""
Finished with the directory, unlock it
"""
self.cv.acquire()
self.dirs.remove(dir_)
self.cv.notify_all()
self.cv.release()
示例11: TestBackend
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class TestBackend(Backend):
def __init__(self, queue):
self.lock = Condition()
queue._set_backend(self)
# Statistics
self.notifies = 0
def start(self):
pass
def stop(self):
pass
def start_feedback(self):
pass
def queue_lock(self):
return self.lock
def queue_notify(self):
self.notifies += 1
self.lock.notify_all()
def sleep(self):
pass
示例12: Presponse
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class Presponse(PktHandler):
def __init__(self):
self.ping_response_wait = Condition()
'''
To wait for a ping response, do the following:{
start = time.time()
with Presponse.ping_response_wait:
Presponse.ping_response_wait.wait(5) # Standard timeout in PING latency is 5.
end = time.time()
}
(end - start) is the ping latency.
'''
def handle(self, packet_map):
with self.ping_response_wait:
self.ping_response_wait.notify_all()
return None
def getproperties(self):
return {
'DisplayName':'Ping-Response Notifier',
'CodeName':'PRESPONSE_NOTIFY',
'PacketType':'PRESPONSE',
'Version':0.01
}
示例13: Timer
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class Timer(EventProducer): #{{{
"""
Timer implementation; richer than threading.Timer: allows to periodically fire one callback for
some time, finally it fires second callback. Timer instance is tightly bound to invoker object
which is used to execute callbacks.
"""
def __init__(self, invoker, total=None, interval=None, callback=__pass__, end_callback=__pass__, user_data=None):
"""Run for `total` seconds, every `interval` call `callback`, finally
call `end_callback`. If `interval` is not set, only `end_callback` is
called once.
If `total` is None, call until canceled.
"""
EventProducer.__init__(self, invoker)
self.interval = interval if interval is not None else float('inf')
self.total = total if total is not None else float('inf')
if user_data:
self.callback = partial(callback, user_data=user_data)
else:
self.callback = callback
self.end_callback = end_callback
self.user_data = user_data
self.cancelled = False
self.last_time = time()
self.timer_invoker = Invoker()
self.timer_invoker.name = 'timer invoker'
self.end_cnd = Condition()
def start(self):
def __callback__():
if not self.cancelled:
self.callback(self.time_left)
self.timer_invoker.invoke(tick)
def tick():
to_sleep = max(0, min(self.time_left, self.interval))
with self.end_cnd:
self.end_cnd.wait(to_sleep)
act_time = time()
self.time_left = self.total - (act_time - self.begin_time)
if not self.cancelled:
if self.time_left > 0:
self.invoker.invoke(__callback__)
else:
self.invoker.invoke(self.end_callback)
self.timer_invoker.cancel()
self.begin_time = time()
self.time_left = self.total
self.timer_invoker.start()
self.timer_invoker.invoke(tick)
return "timer_start_return"
def cancel(self):
self.cancelled = True
self.timer_invoker.cancel()
with self.end_cnd:
self.end_cnd.notify_all()
示例14: Future
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class Future(object):
class CallbackRecord(object):
def __init__(self, callback, trigger_on_cancel):
self.callback = callback
self.trigger_on_cancel = trigger_on_cancel
def __init__(self):
self.__result = None
self.finished = False
self.cancelled = False
self.__callbacks = []
self.__lock = Condition()
self.logger = logging.getLogger(__name__)
def fulfill(self, result=None):
with self.__lock:
self.__result = result
self.__do_finish()
def __do_finish(self):
self.finished = True
self.__fire_callbacks()
self.__lock.notify_all()
def cancel(self):
with self.__lock:
self.cancelled = True
self.__do_finish()
def __fire_callbacks(self):
for callback_record in self.__callbacks:
self.__fire_callback(callback_record)
def __do_fire(self, callback):
#pylint: disable=bare-except
try:
callback(self.__result)
except:
self.logger.exception("Exception occurred running future callback")
def __fire_callback(self, callback_record):
if callback_record.trigger_on_cancel or not self.cancelled:
common_pool.submit(self.__do_fire(callback_record.callback))
def join(self):
with self.__lock:
while not self.finished:
self.__lock.wait()
def add_callback(self, callback, trigger_on_cancel=True):
callback_record = Future.CallbackRecord(callback, trigger_on_cancel)
with self.__lock:
if self.finished:
self.__fire_callback(callback_record)
else:
self.__callbacks.append(callback_record)
示例15: __init__
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify_all [as 别名]
class CameraWorker:
def __init__(self):
self.frame_cd = Condition()
self.frame = False
self.keep_working = True
self.worker = Thread(target=self.work)
self.worker.start()
def work(self):
camera = picamera.PiCamera()
camera.hflip = config_get("raspberry_horizontal_flip")
camera.vflip = config_get("raspberry_vertical_flip")
camera.resolution = (
config_get("raspberry_resolution_x"),
config_get("raspberry_resolution_y")
)
camera.start_preview()
time.sleep(2)
stream = io.BytesIO()
released = True
try:
for notUsed in camera.capture_continuous(stream, format='jpeg', resize=None, quality=config_get("raspberry_base_quality")):
self.frame_cd.acquire()
released = False
self.frame = stream.getvalue()
self.frame_cd.notify_all()
self.frame_cd.release()
released = True
stream.seek(0)
stream.truncate()
if not self.keep_working:
break
finally:
camera.close()
if not released: self.frame_cd.release()
def close(self):
self.keep_working = False
self.worker.join()
def get_picture(self):
self.frame_cd.acquire()
self.frame_cd.wait(5)
frame_cpy = self.frame
self.frame_cd.release()
return frame_cpy
def stream(self):
try:
self.frame_cd.acquire()
while self.keep_working:
self.frame_cd.wait(5)
yield self.frame
finally:
self.frame_cd.release()