本文整理汇总了Python中threading.Condition.notify方法的典型用法代码示例。如果您正苦于以下问题:Python Condition.notify方法的具体用法?Python Condition.notify怎么用?Python Condition.notify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Condition
的用法示例。
在下文中一共展示了Condition.notify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class Mailboxmonitor:
def __init__(self):
self.mailboxlock = Lock()
self.mailidentifier = 0
self.fileHandle = open("mailbox", "w")
self.backupthreadactive = 0
self.backupthreadswaiting = 0
self.waitingforbackuptocomplete = Condition(self.mailboxlock)
self.backupneededcond = Condition(self.mailboxlock)
def delivermail(self, clientname, mailsender, mailreceiver, mailcontent):
with self.mailboxlock:
#if back up is happening stop writes everywhere
while self.backupthreadactive == 1:
self.waitingforbackuptocomplete.wait()
mail = "Received from " + str(clientname) + " by pm489 (CS4410MP3)\n"
self.mailidentifier += 1
mail += "Number: " + str(self.mailidentifier) + "\n"
mail += "From: " + str(mailsender) + "\n"
for i in range(0, len(mailreceiver)):
mail += "To: " + str(mailreceiver[i]) + "\n"
mail += "\n"
mail += mailcontent + "\n"
mail += "\n"
while self.backupthreadactive == 1: #if back up is happening stop writes everywhere
print "worker sleeping"
self.waitingforbackuptocomplete.wait()
self.fileHandle.write(mail)
self.fileHandle.flush()
if self.mailidentifier%32 == 0 and self.backupthreadswaiting > 0:
self.backupthreadactive = 1
self.backupthreadswaiting = 0
self.backupneededcond.notify()
return self.mailidentifier
def startbackupthread(self):
with self.mailboxlock:
while self.backupthreadactive==0:
#print "backup slept"
self.backupthreadswaiting = 1
self.backupneededcond.wait()
def initiatebackup(self, lastbackedmessage):
with self.mailboxlock:
if( self.mailidentifier%32 != 0):
print "Something went very horribly wrong"
newfilename = "mailbox." + str(lastbackedmessage+1)+"-"+ str(lastbackedmessage+32)
self.fileHandle.close()
os.rename("mailbox", newfilename)
self.fileHandle = open("mailbox", "w")
lastbackedmessage += 32
self.backupthreadactive = 0
self.waitingforbackuptocomplete.notifyAll() #wake up all waiting threads to write
return lastbackedmessage
示例2: DataQueue
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class DataQueue ( Queue ):
def __init__ ( self, count ):
Queue.__init__(self)
self._count = count
self._cond = Condition()
def get ( self, block = True, timeout = None ):
self._cond.acquire()
if self.empty():
if not self._count:
raise Empty()
elif block:
self._cond.wait(timeout)
if self.empty() and not self._count:
self._cond.release()
raise Empty()
self._cond.release()
return Queue.get(self, block, timeout)
def put ( self, data ):
self._cond.acquire()
self._count = self._count - 1
Queue.put(self, data)
if self._count:
self._cond.notify()
else:
self._cond.notifyAll()
self._cond.release()
def remain ( self ):
return self._count + self.unfinished_tasks
示例3: __init__
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class DirtyBit:
def __init__(self):
self._mon = RLock()
self._rc = Condition(self._mon)
self._dirty = 0
def clear(self):
self._mon.acquire()
self._dirty = 0
#self._rc.notify() only interested in knowing when we are dirty
self._mon.release()
def set(self):
self._mon.acquire()
self._dirty = 1
self._rc.notify()
self._mon.release()
def value(self):
return self._dirty
def wait(self):
self._mon.acquire()
self._rc.wait()
self._mon.release()
示例4: External_command
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class External_command(object):
work_available = None
work = None
def __init__(self, command, max_workers = _MAX_WORKERS):
self.work_available = Condition()
self.work = []
for i in range(0, max_workers):
_Worker(command, self)
def process_command(self, data, result_callback, *callback_parameters):
wi = Work_item(tuple(data), result_callback, callback_parameters)
self.work_available.acquire()
self.work.append(wi)
self.work_available.notify()
self.work_available.release()
return wi
def shutdown(self):
self.work_available.acquire()
self.work.append(None)
self.work_available.notify()
self.work_available.release()
def process_result(self, result_callback, result, *callback_parameters):
try:
result_callback(result, *callback_parameters)
except:
print datetime.now(), 'External_command: unhandled exception in external command results callback'
print '-' * 70
print_exc(file = stdout)
print '-' * 70
stdout.flush()
示例5: External_command
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class External_command(object):
work_available = None
work = None
def __init__(self, command, max_workers = _MAX_WORKERS):
self.work_available = Condition()
self.work = []
for i in range(0, max_workers):
_Worker(command, self)
def process_command(self, data, result_callback, *callback_parameters):
wi = Work_item(tuple(data), result_callback, callback_parameters)
self.work_available.acquire()
self.work.append(wi)
self.work_available.notify()
self.work_available.release()
return wi
def shutdown(self):
self.work_available.acquire()
self.work.append(None)
self.work_available.notify()
self.work_available.release()
def process_result(self, result_callback, result, *callback_parameters):
try:
result_callback(result, *callback_parameters)
except Exception as ex:
if isinstance(ex, SystemExit):
raise
dump_exception('External_command: unhandled exception in external command results callback')
示例6: NotificationQueue
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class NotificationQueue(Queue):
""" A queue class that notifies waiting threads when the queue is available for
reading."""
def __init__(self):
""" Constructor."""
Queue.__init__(self)
self.lock = Condition()
def get(self):
""" Get an item from the queue. This method is thread-safe.
Method must be called on a non-empty queue.
Return : the first item from the queue
Raises: a EmptyQueue exeception
"""
return Queue.get(self, False)
def put(self, item):
""" Add a new item to the queue. This method is thread-safe.
Threads that are waiting for get an item are notified.
item: new item to add to the queue.
Return : None
"""
self.lock.acquire()
Queue.put(self, item)
self.lock.notify()
self.lock.release()
def acquire(self):
self.lock.acquire()
def release(self):
self.lock.release()
def wait(self):
self.lock.wait()
示例7: RepceJob
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class RepceJob(object):
"""class representing message status we can use
for waiting on reply"""
def __init__(self, cbk):
"""
- .rid: (process-wise) unique id
- .cbk: what we do upon receiving reply
"""
self.rid = (os.getpid(), thread.get_ident(), time.time())
self.cbk = cbk
self.lever = Condition()
self.done = False
def __repr__(self):
return ':'.join([str(x) for x in self.rid])
def wait(self):
self.lever.acquire()
if not self.done:
self.lever.wait()
self.lever.release()
return self.result
def wakeup(self, data):
self.result = data
self.lever.acquire()
self.done = True
self.lever.notify()
self.lever.release()
示例8: FileTrigger
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class FileTrigger(Thread):
"""Wait for a file.
"""
def __init__(self, filename):
Thread.__init__(self)
self.filename = filename
self.loop = True
self.cond = Condition()
# self.start()
self.exit_status = 0
def run(self):
while self.loop:
self.cond.acquire()
# Polling is ugly, this should be replaced when possible by inotify.
if os.path.exists(self.filename):
# Could we use yield instead ?
self.cond.release()
return
self.cond.wait(1)
self.cond.release()
def cancel(self):
self.loop = False
self.exit_status = 1
self.cond.acquire()
self.cond.notify()
self.cond.release()
def __repr__(self):
return "File trigger " + self.filename
示例9: TimeTrigger
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class TimeTrigger(Thread):
"""Wait for a given time.
"""
def __init__(self, time):
Thread.__init__(self)
self.time = time
self.loop = True
self.cond = Condition()
# self.start()
self.exit_status = 0
def run(self):
while self.loop and self.time > datetime.utcnow():
self.cond.acquire()
now = datetime.utcnow()
diff = (self.time - now).seconds + (self.time - now).microseconds / 1000000.0
self.cond.wait(diff)
self.cond.release()
def cancel(self):
self.loop = False
self.exit_status = 1
self.cond.acquire()
self.cond.notify()
self.cond.release()
def __repr__(self):
return "Time trigger " + str(self.time)
示例10: AutoFetcher
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class AutoFetcher(Thread):
_interval = 60 * 60 # = 1 hour
_inactive_block = None
def __init__(self):
super(AutoFetcher, self).__init__()
self._inactive_block = Condition()
self.daemon = True
def trigger(self):
with self._inactive_block:
self._inactive_block.notify()
def run(self):
while True:
self.launch_task()
time.sleep(self._interval)
if not center.main_win.win.isActiveWindow():
logging.debug('AutoFetcher paused.')
with self._inactive_block:
self._inactive_block.wait()
logging.debug('AutoFetcher resumed.')
@qt.run_in_qt
def launch_task(self):
tasks.run_task(tasks.FetchTask())
if center.settings['update_notify'] and '-dev' not in center.VERSION:
tasks.run_task(tasks.CheckUpdateTask())
示例11: Semaphore
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class Semaphore(object):
def __init__(self, count=1):
if count < 1:
raise ValueError('Semaphore count should be at least 1.')
self._count = count
self._cond = Condition(Lock())
def P(self):
'''Acquire a lock.
Block until acquired successfully.
'''
with self._cond:
while self._count <= 0:
self._cond.wait() # block and wait for the lock.
else:
self._count = self._count - 1
def V(self):
'''Release a lock.'''
with self._cond:
self._count = self._count + 1
self._cond.notify() # wake up a waiting thread.
示例12: __init__
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class MasterSlaveLock:
def __init__(self):
self.__master_lock = Lock()
self.__slave_locks_counter_condition = Condition()
self.__slave_locks_count = 0
def acquire_master(self):
self.__master_lock.acquire()
# wait for all slavelocks to unlock
self.__slave_locks_counter_condition.acquire()
while self.__slave_locks_count != 0:
self.__slave_locks_counter_condition.wait()
self.__slave_locks_counter_condition.release()
def release_master(self):
self.__master_lock.release()
def acquire_slave(self):
# stop further slave locks here, when master-process is waiting for a full stop of slave processes
self.__master_lock.acquire()
self.__master_lock.release()
self.__slave_locks_counter_condition.acquire()
self.__slave_locks_count += 1
self.__slave_locks_counter_condition.release()
def release_slave(self):
self.__slave_locks_counter_condition.acquire()
self.__slave_locks_count -= 1
if not self.__slave_locks_count: # we released the last lock, notify (maybe) waiting master-process
self.__slave_locks_counter_condition.notify()
self.__slave_locks_counter_condition.release()
示例13: _Timer
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class _Timer(object):
def __init__(self, event_engine, seconds=1):
# 计时器,用于触发计时器事件
self._timer = Thread(target = self._run_timer)
self._timer.daemon = True
self._timer_active = False
self._timer_sleep = seconds
self._timer_pause_condition = Condition(Lock())
self._event_engine = event_engine
def set_timer(self, seconds):
self._timer_sleep = seconds
def start_timer(self):
self._timer_active = True
self._timer.start()
def pause_timer(self):
self._timer_active = False
self._timer_pause_condition.acquire()
def resume_timer(self):
self._timer_active = True
self._timer_pause_condition.notify()
self._timer_pause_condition.release()
def _run_timer(self):
event = Event(route=EVENT_TIMER)
while True:
with self._timer_pause_condition:
if not self._timer_active:
self._timer_pause_condition.wait()
self._event_engine.emit(event)
# 等待
sleep(self._timer_sleep)
示例14: __init__
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class Club:
def __init__(self):
self.clubLock = Lock()
self.redditCond = Condition(self.clubLock)
self.fourchannerCond = Condition(self.clubLock)
self.fourchannerCount = 0
self.redditorCount = 0
def redditor_enter(self):
with self.clubLock:
while self.fourchannerCount > 0 :
self.redditCond.wait()
self.redditorCount = self.redditorCount + 1
def redditor_exit(self):
with self.clubLock:
self.redditorCount = self.redditorCount - 1
if self.redditorCount == 0 :
self.fourchannerCond.notify()
def fourchanner_enter(self):
with self.clubLock:
while self.redditorCount > 0 :
self.fourchannerCond.wait()
self.fourchannerCount = self.fourchannerCount + 1
def fourchanner_exit(self):
with self.clubLock:
self.fourchannerCount = self.fourchannerCount - 1
if self.fourchannerCount == 0:
self.redditCond.notify()
示例15: TmThread
# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import notify [as 别名]
class TmThread(Thread):
def __init__(self, target, args): # name, event_for_wait, event_for_set
Thread.__init__(self) # , target=target, args=args)
self.__target = target
self.__args = args
self.__kwargs = None
self.priority = 0
self.time = 0
#flag to Finish thread
self.Finishd = False
# Explicitly using Lock over RLock since the use of self.Finishd
# break reentrancy anyway, and I believe using Lock could allow
# one thread to Finish the worker, while another resumes; haven't
# checked if Condition imposes additional limitations that would
# prevent that. In Python 2, use of Lock instead of RLock also
# boosts performance.
self.Finish_cond = Condition(Lock())
def Finish(self):
self.Finishd = True
# If in sleep, we acquire immediately, otherwise we wait for thread
# to release condition. In race, worker will still see self.Finishd
# and begin waiting until it's set back to False
self.Finish_cond.acquire()
#should just resume the thread
def resume(self):
self.Finishd = False
# Notify so thread will wake after lock released
self.Finish_cond.notify()
# Now release the lock
self.Finish_cond.release()