本文整理汇总了Python中threading.Event.isSet方法的典型用法代码示例。如果您正苦于以下问题:Python Event.isSet方法的具体用法?Python Event.isSet怎么用?Python Event.isSet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Event
的用法示例。
在下文中一共展示了Event.isSet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RunThread
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class RunThread(Thread):
'''Very basic thread in which to run the sleep loop while the callbacks are running'''
def __init__(self):
super(RunThread,self).__init__()
self._stop = Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def run(self):
second_count = 0
minute_count = 0
while True:
time.sleep(1) # The callback will be firing all during this point
if second_count % 60 == 0:
print "{} minutes".format(minute_count)
minute_count += 1
print ".",
second_count += 1
if self._stop.isSet():
return
示例2: MarkerThread
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class MarkerThread(Thread):
def __init__(self, da, zl, marker, coord, conf, pixDim):
Thread.__init__(self)
self.da = da
self.update = Event()
self.update.set()
self.__stop = Event()
self.zl = zl
self.marker = marker
self.coord = coord
self.conf = conf
self.pixDim = pixDim
self.img = self.marker.get_marker_pixbuf(zl)
def run(self):
while not self.__stop.isSet():
self.update.wait()
self.update.clear()
self.draw_markers()
def stop(self):
self.__stop.set()
self.update.set()
def draw_markers(self):
for string in self.marker.positions.keys():
if self.update.isSet() or self.__stop.isSet():
break
mpos = self.marker.positions[string]
if (self.zl <= mpos[2]) and (mpos[0], mpos[1]) != (self.coord[0], self.coord[1]):
gtk.threads_enter()
try:
self.da.draw_marker(self.conf, mpos, self.zl, self.img, self.pixDim, string)
finally:
gtk.threads_leave()
示例3: StreamWrapperHelper
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class StreamWrapperHelper(Thread):
def __init__(self, queue):
Thread.__init__(self)
self.__stop = Event()
self.__queue = queue
self.__full = Event()
self.start()
def run(self):
while True:
if self.__stop.isSet():
return
stream = tweetstream.SampleStream(u'soldierkam', os.environ["PASSWORD"])
for s in stream:
try:
if self.__stop.isSet():
stream.close()
return
self.__queue.put(s, block=False)
self.__full.clear()
except Full:
if not self.__full.isSet():
logger.warn("Queue is full!!")
self.__full.set()
def close(self):
self.__stop.set()
示例4: test_threadpool
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
def test_threadpool():
pool = ThreadPool(core_threads=2, keepalive=0)
event1 = Event()
event2 = Event()
event3 = Event()
pool.submit(event1.set)
pool.submit(event2.set)
pool.submit(event3.set)
event1.wait(1)
event2.wait(1)
event3.wait(1)
assert event1.isSet()
assert event2.isSet()
assert event3.isSet()
sleep(0.3)
eq_(repr(pool), '<ThreadPool at %x; threads=2/20>' % id(pool))
pool.shutdown()
eq_(repr(pool), '<ThreadPool at %x; threads=0/20>' % id(pool))
# Make sure double shutdown is ok
pool.shutdown()
# Make sure one can't submit tasks to a thread pool that has been shut down
assert_raises(RuntimeError, pool.submit, event1.set)
示例5: Worker
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class Worker(Thread):
""" 工作线程,取出线程池中的任务,执行任务中指定的函数,完成任务功能"""
def __init__(self, task_queue, res_queue, poll_timeout=2, **kwds):
Thread.__init__(self, **kwds)
logger.debug('Worker Thread id :: %s', id(self))
self.setDaemon(True)
self.task_queue = task_queue
self.result_queue = res_queue
self._poll_timeout = poll_timeout
self._dismissed = Event()
self.start()
def run(self):
"""重复取出 task_queue 里的任务并执行,直到通知其退出。"""
while True:
if self._dismissed.isSet():
break
try:
task = self.task_queue.get(
block=True, timeout=self._poll_timeout)
except Queue.Empty:
continue
else:
if self._dismissed.isSet():
# 线程退出,把请求放回 task_queue
self.task_queue.put(task)
break
result = task.func(*task.args, **task.kwds)
logger.debug('Worker Thread id :: %s' % id(self))
self.result_queue.put((task, result))
def dismiss(self):
"""当前任务结束后,退出线程"""
self._dismissed.set()
示例6: AsyncTBWriter
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class AsyncTBWriter():
"Callback for GANLearners that writes to Tensorboard. Extends LearnerTensorboardWriter and adds output image writes."
def __init__(self):
super().__init__()
self.stop_request = Event()
self.queue = Queue()
self.thread = Thread(target=self._queue_processor, daemon=True)
self.thread.start()
def request_write(self, request: TBWriteRequest)->None:
"Queues up an asynchronous write request to Tensorboard."
if self.stop_request.isSet(): return
self.queue.put(request)
def _queue_processor(self)->None:
"Processes queued up write requests asynchronously to Tensorboard."
while not self.stop_request.isSet():
while not self.queue.empty():
if self.stop_request.isSet(): return
request = self.queue.get()
request.write()
sleep(0.2)
#Provided this to stop thread explicitly or by context management (with statement) but thread should end on its own
# upon program exit, due to being a daemon. So using this is probably unecessary.
def close(self)->None:
"Stops asynchronous request queue processing thread."
self.stop_request.set()
self.thread.join()
# Nothing to do, thread already started. Could start thread here to enforce use of context manager
# (but that sounds like a pain and a bit unweildy and unecessary for actual usage)
def __enter__(self): pass
def __exit__(self, exc_type, exc_value, traceback): self.close()
示例7: ChatReciever
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class ChatReciever(Thread):
def __init__(self, host, timeout=10):
Thread.__init__(self)
self.onMsg = []
self.host = host
self.timeout = timeout
self._stop = Event()
self.start()
def regHandler(self, type, func):
if type == 'msg':
self.onMsg.append(func)
else:
raise UnknownHandlerException()
def run(self):
lastmsg = 0
while 1:
if self._stop.isSet(): break
try:
output = urllib2.urlopen(urllib2.Request(self.host+"/taigachat/list.json", urllib.urlencode({"lastrefresh":lastmsg})), timeout=self.timeout).read()
new = bool(lastmsg)
lastmsg = json.loads(output).get("lastrefresh")
msglist = re.findall('<li.*?data-time="(.*?)".*?class="username" itemprop="name">(.*?)<\/a>.*?messagetext ugc\'>(.*?)</div> <\/li>', json.loads(output.replace("\\n","")).get("templateHtml"))
for msg in msglist:
for f in self.onMsg:
f(msg[0], HTMLParser().unescape(re.sub('<[^>]*>', '', msg[1])), HTMLParser().unescape(re.sub('<[^>]*>', '', re.sub('<img.*?alt="(.*?)".*?>',r'\1', msg[2]))), new)
except Exception as e:
#print traceback.format_exc()
sys.stderr.write('Error while getting messages: ' + str(e) + '\n')
if self._stop.isSet(): break
sleep(2)
def stop(self):
self._stop.set()
示例8: PrinterThread
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class PrinterThread(Thread):
def __init__(self, stdout_queue, total_jobs):
super(PrinterThread, self).__init__()
self._stop = Event()
self.stdout_queue = stdout_queue
self.total_jobs = total_jobs
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def run(self):
hash_to_counter = {}
job_ids_done = set()
while not self._stop.isSet():
(hash_, message) = self.stdout_queue.get()
job_ids_done.add(hash_)
if message is None: # job is done
break
else:
print(
"%s %s" %
(colored(
"[{jobs_done}/{total_jobs}]".format(
jobs_done=len(job_ids_done),
total_jobs=self.total_jobs),
"magenta",
attrs=["bold"]),
message))
self.stdout_queue.task_done()
示例9: CreateTurtleString
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class CreateTurtleString(Thread):
def __init__(self, string, rules, iterations, *args, **kwargs):
super(CreateTurtleString, self).__init__(*args, **kwargs)
self.string = string
self.rules = rules
self.iterations = iterations
self._job_done = Event()
self._stop_creating = Event()
def job_done(self):
return self._job_done.isSet()
def stop_creating(self):
self._stop_creating.set()
def run(self):
string = self.string
iterations = self.iterations
rules = self.rules
for _ in range(iterations):
if self._stop_creating.isSet():
break
string = cached_expand_string(string, rules)
self.string = string
self._job_done.set()
示例10: FileSearchServer
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class FileSearchServer(Thread):
""" Thread which answers to file/tag queries sent through unix socket. """
def __init__(self, pname='SET_ME_PLEASE'):
Thread.__init__(self)
self.name = "%s/%s" % (
pname, str(self.__class__).rsplit('.', 1)[1].split("'")[0])
# old socket from a crashed daemon ?
# remove it, the ThreadingUnixStreamServer will create it.
#if os.path.exists(socket_path): os.unlink(socket_path)
self._stop_event = Event()
self.server = ThreadingTCPServer(('127.0.0.1', searcher_port), FileSearchRequestHandler)
self.server.allow_reuse_address = True
# TODO: the socket is set to non-blocking to be able to gracefully terminate the thread,
# but this could lead to CPU hogging problems. VERIFY THIS !!
self.server.socket.setblocking(False)
def run(self):
logging.progress("%s: thread running." % (self.getName()))
#os.chmod(socket_path, stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IWGRP|stat.S_IROTH|stat.S_IWOTH)
while not self._stop_event.isSet():
self.server.handle_request()
time.sleep(0.01)
logging.progress("%s: thread ended." % (self.getName()))
def stop(self):
if not self._stop_event.isSet():
logging.progress("%s: stopping thread." % (self.getName()))
self._stop_event.set()
self.server.socket.close()
self.server.server_close()
if os.path.exists(socket_path):
os.unlink(socket_path)
示例11: StatusMonitor
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class StatusMonitor(Loggable):
# valve_manager = None
_stop_evt = None
_clients = 0
state_freq = Int(3)
lock_freq = Int(5)
owner_freq = Int(5)
update_period = Int(2)
def start(self, vm):
if not self._clients:
if self._stop_evt:
self._stop_evt.set()
self._stop_evt.wait(0.25)
self._stop_evt = Event()
self._iter(1, vm)
else:
self.debug('Monitor already running')
self._clients += 1
def isAlive(self):
if self._stop_evt:
return not self._stop_evt.isSet()
def stop(self):
self._clients -= 1
if not self._clients:
self._stop_evt.set()
self.debug('Status monitor stopped')
else:
self.debug('Alive clients {}'.format(self._clients))
def _iter(self, i, vm):
if vm is None:
self.debug('No valve manager')
return
if not i % self.state_freq:
vm.load_valve_states()
if not i % self.lock_freq:
vm.load_valve_lock_states()
if not i % self.owner_freq:
vm.load_valve_owners()
if i > 100:
i = 0
if not self._stop_evt.isSet():
do_after(self.update_period * 1000, self._iter, i + 1, vm)
#============= EOF =============================================
示例12: testBlocking
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
def testBlocking(self):
event = Event()
getter = GetMessageProcess(self._queue, event)
getter.start()
time.sleep(1)
self.assertFalse(event.isSet())
self._queue.append(MESSAGE)
event.wait(5)
self.assertTrue(event.isSet())
示例13: __init__
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class AgentLogicBase:
def __init__(self):
self.wait_stop = Event()
if (platform.system() == 'Windows') or (platform.system() == 'Microsoft'):
vport_name = '\\\\.\\Global\\com.eayun.eayunstack.0'
else:
vport_name = '/dev/virtio-ports/com.eayun.eayunstack.0'
self.vio = VirtIoChannel(vport_name)
self.commandHandler = None
def _send(self, name, arguments=None):
self.vio.write(name, arguments or {})
def run(self):
thread.start_new_thread(self.doListen, ())
while not self.wait_stop.isSet():
self.wait_stop.wait(1)
def stop(self):
self.wait_stop.set()
def doListen(self):
if self.commandHandler is None:
return
while not self.wait_stop.isSet():
try:
cmd, args = self.vio.read()
if cmd:
self.parseCommand(cmd, args)
except:
pass
def parseCommand(self, command, args):
if command == 'get_infomation':
name = args.get('name')
result = self.commandHandler.get_infomation(name)
self._send('get_infomation', {'result': result})
elif command == 'execute_script':
path = args.get('path')
type = args.get('type')
result = self.commandHandler.execute_script(path, type)
self._send('execute_script', {'result': result})
elif command == 'execute_command':
cmd = args.get('cmd')
try:
result = self.commandHandler.execute_command(cmd)
self._send('execute_command', {'result': result})
except:
self._send('execute_command', {'result': '0e0r0r0o0r1'})
elif command == 'echo':
self._send('echo', args)
else:
self._send(command, {'result': '0e0r0r0o0r0'})
示例14: testBlocking
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
def testBlocking(self):
event = Event()
getter = GetItemProcess(self._queue, event)
getter.start()
time.sleep(1)
self.assertFalse(event.isSet())
self._queue.append(TEST_ITEM)
event.wait(5)
self.assertTrue(event.isSet())
示例15: DrawTurtle
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import isSet [as 别名]
class DrawTurtle(Thread):
def __init__(self, canvas, turtle, colors={}, **kwargs):
super(DrawTurtle, self).__init__(**kwargs)
self._stop_drawing = Event()
self.canvas = canvas
self.turtle = turtle
self.colors = colors
def stop_drawing(self):
self._stop_drawing.set()
def run(self):
self.canvas.begin_new()
color = self.colors["1"]
# Calculate size, and scale to fill the frame
t_width = self.turtle.rightmost[0] - self.turtle.leftmost[0]
t_height = self.turtle.bottommost[1] - self.turtle.topmost[1]
c_width = int(self.canvas['width'])
c_height = int(self.canvas['height'])
if t_width / t_height > 1: # fat image scale according to width
scale_factor = c_width / t_width
else:
scale_factor = c_height / t_height
left_margin = (c_width - scale_factor*t_width) / 2
top_margin = (c_height - scale_factor*t_height) / 2
x_shift = left_margin - scale_factor*self.turtle.leftmost[0]
y_shift = top_margin - scale_factor*self.turtle.topmost[1]
coordinates = []
for item in self.turtle.lines:
if self._stop_drawing.isSet():
return
if isinstance(item, PlaceHolder):
coordinates.append(item)
else:
coordinates.append((item[0]*scale_factor+x_shift,
item[1]*scale_factor+y_shift,
item[2]*scale_factor+x_shift,
item[3]*scale_factor+y_shift))
for item in coordinates:
if self._stop_drawing.isSet():
return
if isinstance(item, PlaceHolder): # not a list of coordinates
if item.value in self.colors:
color = self.colors[item.value]
else:
self.canvas.queue_line(item, color)