本文整理汇总了Python中threading.current_thread方法的典型用法代码示例。如果您正苦于以下问题:Python threading.current_thread方法的具体用法?Python threading.current_thread怎么用?Python threading.current_thread使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading
的用法示例。
在下文中一共展示了threading.current_thread方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cron_task_host
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def cron_task_host():
"""定时任务宿主, 每分钟检查一次列表, 运行时间到了的定时任务"""
while True:
# 当全局开关关闭时, 自动退出线程
if not enable_cron_tasks:
if threading.current_thread() != threading.main_thread():
exit()
else:
return
sleep(60)
try:
task_scheduler.run()
except: # coverage: exclude
errprint('ErrorDuringExecutingCronTasks')
traceback.print_exc()
示例2: acceptThread
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def acceptThread(parameters):
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
acceptor.bind(('', int(parameters['listenPort'])))
acceptor.listen(5)
cur_thread = threading.current_thread()
logger.info("Listening to connections on port " + str(parameters['listenPort']) + '\n')
while True:
(clientSock, clientAddr) = acceptor.accept()
print "==== Output Request ====="
msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
logger.info(msg)
thread3 = threading.Thread(target=sendFile, args=(clientSock, parameters))
thread3.daemon = True
thread3.start()
acceptor.close()
return
示例3: acceptThread
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def acceptThread():
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
acceptor.bind(('', int(uploadPort)))
acceptor.listen(5)
cur_thread=threading.current_thread()
while True:
(clientSock,clientAddr)=acceptor.accept()
print "====Output Request:"
msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
print msg
thread3=threading.Thread(target=sendFile(clientSock))
thread3.daemon=True
thread3.start()
#thread3.join()
acceptor.close()
return
示例4: _app
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def _app() -> Quart:
app = Quart(__name__)
@app.route("/", methods=["GET", "POST"])
def index() -> ResponseReturnValue:
return request.method
@app.route("/gen")
def gen() -> ResponseReturnValue:
def _gen() -> Generator[bytes, None, None]:
yield b"%d" % threading.current_thread().ident
for _ in range(2):
yield b"b"
return _gen(), 200
return app
示例5: process_request
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def process_request(self, environ) -> bool:
"""Process the incoming Flask request."""
# Bot Service doesn't handle anything over 256k
length = int(environ.get("CONTENT_LENGTH", "0"))
if length > 256 * 1024:
print(f"request too long - rejected")
else:
body_bytes = environ["wsgi.input"].read(length)
environ["wsgi.input"] = BytesIO(body_bytes)
body_unicode = body_bytes.decode("utf-8")
# Sanity check JSON
if body_unicode is not None:
# Integration layer expecting just the json text.
_REQUEST_BODIES[current_thread().ident] = body_unicode
return True
示例6: create_dict
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def create_dict(self):
"""Create a new dict for the current thread, and return it."""
localdict = {}
key = self.key
thread = current_thread()
idt = id(thread)
def local_deleted(_, key=key):
# When the localimpl is deleted, remove the thread attribute.
thread = wrthread()
if thread is not None:
del thread.__dict__[key]
def thread_deleted(_, idt=idt):
# When the thread is deleted, remove the local dict.
# Note that this is suboptimal if the thread object gets
# caught in a reference loop. We would like to be called
# as soon as the OS-level thread ends instead.
local = wrlocal()
if local is not None:
dct = local.dicts.pop(idt)
wrlocal = ref(self, local_deleted)
wrthread = ref(thread, thread_deleted)
thread.__dict__[key] = wrlocal
self.dicts[idt] = wrthread, localdict
return localdict
示例7: run
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def run(self):
"""Connect to the server and start the loop in its thread. Retry if requested"""
self.mumble_thread = threading.current_thread()
# loop if auto-reconnect is requested
while True:
self.init_connection() # reset the connection-specific object members
self.connect()
self.loop()
if not self.reconnect or not self.parent_thread.is_alive():
break
time.sleep(PYMUMBLE_CONNECTION_RETRY_INTERVAL)
示例8: get_sizes
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def get_sizes(jsn):
thrd = threading.current_thread()
logging.info('starting thread '+str(thrd.ident)+' ...')
try:
while True:
if queue.empty() == True:
break
itm = queue.get()
logging.info(str(thrd.ident)+' :' +str(itm))
val = get_remote_size(itm)
if val != None: jsn[itm]['objsize'] = val
queue.task_done()
except Queue.Empty:
pass
logging.info('thread '+str(thrd.ident)+' done...')
#get_sizes
#---------------------------------------------------------------------------------
示例9: terminate
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def terminate(self, block=True, timeout=30):
"""Terminate this job, the current thread will blocked util
the job is terminate finished if block is True """
if self.is_stopped():
_logger.info('Job already been stopped.')
return
if self._running_thread == threading.current_thread():
_logger.warning('Job cannot terminate itself.')
return
_logger.info('Stopping job')
self._should_stop = True
if not block:
return
if not self._terminated.wait(timeout):
_logger.warning('Terminating job timeout.')
示例10: run
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def run(self):
"""Start job and exit util meet stop condition. """
_logger.info('Start to process job')
self._stopped = False
try:
self._running_thread = threading.current_thread()
self._run()
except Exception:
_logger.exception('Error encountered while running job.')
raise
finally:
self._terminated.set()
self._stopped = True
_logger.info('Job processing finished')
示例11: _do_admin
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def _do_admin(self):
admin_q = self._admin_queue
resize_win = self._resize_window
while 1:
try:
wakup = admin_q.get(timeout=resize_win + 1)
except queue.Empty:
self._do_resize_according_to_loads()
continue
if wakup is None:
break
else:
self._do_resize_according_to_loads()
log.logger.info("ThreadPool admin thread=%s stopped.",
threading.current_thread().getName())
示例12: then
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def then(self, fn, deferred=False):
result = Future(self._loop)
result._register()
def callback(_):
try:
if deferred:
temp = self._loop.run_later(fn, self.result())
temp.chain(result)
elif not threading.current_thread() is self._loop:
temp = self._loop.run_async(fn, self.result())
temp.chain(result)
else:
result.set_result(fn(self.result()))
except Exception as e:
self.logger.exception(
"Unhandled exception while chaining futures"
)
result.set_exception(e)
except:
result.cancel()
self.add_done_callback(callback)
return result
示例13: run_async
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def run_async(self, func, *args, **kwds):
"""
Fills in a list with the function to be executed in the pomp thread
and wakes up the pomp thread.
"""
future = Future(self)
future._register()
if threading.current_thread() is not self:
self.async_pomp_task.append((future, func, args, kwds))
self._wake_up()
else:
try:
ret = func(*args, **kwds)
except Exception as e:
self.logger.exception(
"Unhandled exception in async task function"
)
future.set_exception(e)
else:
if not isinstance(ret, concurrent.futures.Future):
future.set_result(ret)
else:
ret.chain(future)
return future
示例14: get_feed_dict
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def get_feed_dict(self, dest=None):
tid = threading.current_thread().ident
self.prefetch.setdefault(tid, {'thread': None, 'data': None})
current = self.prefetch[tid]
def assign_thread():
def assign():
current['data'] = self.get_feed_dict_sync()
current['thread'] = threading.Thread(target=assign)
current['thread'].start()
if current['thread'] is None:
assign_thread()
current['thread'].join()
res = current['data']
assign_thread()
return res
示例15: _set_SIGCHLD_handler
# 需要导入模块: import threading [as 别名]
# 或者: from threading import current_thread [as 别名]
def _set_SIGCHLD_handler():
# Windows doesn't support SIGCHLD handler
if sys.platform == 'win32':
return
# can't set signal in child threads
if not isinstance(threading.current_thread(), threading._MainThread):
return
global _SIGCHLD_handler_set
if _SIGCHLD_handler_set:
return
previous_handler = signal.getsignal(signal.SIGCHLD)
if not callable(previous_handler):
previous_handler = None
def handler(signum, frame):
# This following call uses `waitid` with WNOHANG from C side. Therefore,
# Python can still get and update the process status successfully.
_error_if_any_worker_fails()
if previous_handler is not None:
previous_handler(signum, frame)
signal.signal(signal.SIGCHLD, handler)
_SIGCHLD_handler_set = True