本文整理汇总了Python中threading.main_thread函数的典型用法代码示例。如果您正苦于以下问题:Python main_thread函数的具体用法?Python main_thread怎么用?Python main_thread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了main_thread函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: threadManagerRun
def threadManagerRun(self):
#Wait for the main thread to shut down
while(threading.main_thread().is_alive()):
time.sleep(0)
threading.main_thread().join()
self.closed = True
#Shutdown external communications
if (self.serialTalker):
self.serialTalker.shutDown()
#DEBUG: Confirm shutdown control returns to main controller
print("JINX Controller has shut down serial talker")
if (self.serverTalker):
self.serverTalker.shutDown()
#DEBUG: Confirm shutdown control returns to main controller
print("JINX Controller has shut down Server")
#DEBUG: Waiting for threads to close
print("Waiting for serial talker and server to shut down.")
if (self.serialThread.is_alive()):
self.serialThread.join()
if (self.serverThread.is_alive()):
self.serverThread.join()
#DEBUG: Confirm all stopped
print("All from JINX stopped")
示例2: pull_in_the_background
def pull_in_the_background(self):
"""
Keep pulling data in the background.
TODO:
- Stop pulling when running out of memory. Perhaps start deleting rows
that are not in the region of interest?
- Continue to pull data outside the region_of_interest when we got
all of that?
"""
if (not self.stop_pulling) and threading.main_thread().is_alive():
self.pull_region_of_interest()
if (not self.stop_pulling) and threading.main_thread().is_alive():
threading.Timer(10, self.pull_in_the_background).start()
示例3: handle
def handle(self):
# Flush any pending changes. Any updates
# beyond here will be field specific
self.save()
is_main_thread = threading.current_thread() == threading.main_thread()
if is_main_thread:
# Protect ourselves from SIGTERM
def on_sigterm(sig, frame):
self.cancel()
prev_handler = signal.signal(signal.SIGTERM, on_sigterm)
self.start()
try:
yield
except Retry as e:
self.fail(e)
self.reschedule(claim=True)
except Exception as e:
self.fail(e)
raise
else:
# If the handler didn't handle setting a status, assume success
if self.status == self.STATUS.started:
self.succeed()
finally:
if is_main_thread:
# Detach from SIGTERM, resetting the previous handle
signal.signal(signal.SIGTERM, prev_handler)
示例4: asynchronous
def asynchronous(func: Callable[..., Any]):
"""
Wraps a callable so that it is guaranteed to be called in the event loop.
If it returns a coroutine or a Future and the call came from another thread, the coroutine
or Future is first resolved before returning the result to the caller.
"""
@wraps(func, updated=())
def wrapper(*args, **kwargs):
@coroutine
def callback():
try:
retval = func(*args, **kwargs)
if iscoroutine(retval) or isinstance(retval, Future):
retval = yield from retval
except Exception as e:
f.set_exception(e)
except BaseException as e: # pragma: no cover
f.set_exception(e)
raise
else:
f.set_result(retval)
if current_thread() is event_loop_thread:
return func(*args, **kwargs)
else:
f = Future()
event_loop.call_soon_threadsafe(async, callback())
return f.result()
event_loop = get_event_loop()
event_loop_thread = main_thread()
return wrapper
示例5: _run
def _run(self):
parent = threading.main_thread()
if self._restarting:
self._parent._notify_engine_restarted(self)
self._restarting = False
while parent.is_alive():
try:
bytes = self._socket.recv()
message = jcoms.ComsMessage()
message.ParseFromString(bytes)
self._receive(message)
except nanomsg.NanoMsgAPIError as e:
if e.errno != nanomsg.ETIMEDOUT and e.errno != nanomsg.EAGAIN:
raise e
self._process.poll()
if self._process.returncode is not None:
if self._restarting is False and self._stopping is False:
log.error('Engine process terminated with exit code {}\n'.format(self._process.returncode))
break
self._socket.close()
if self._restarting:
log.info('Restarting engine')
self._restarting = False
self._stopping = False
self.start()
else:
self._stopped = True
self._parent._notify_engine_event({ 'type': 'terminated' })
示例6: bind
def bind(self):
assert threading.current_thread() is threading.main_thread()
length = None
first_atname = None
if self.instanced:
instances = None
instanced_first_atname = None
vao = gl.glGenVertexArrays(1)
gl.glBindVertexArray(vao)
if self.indices:
self.indices.bind()
for atname, at in self.attributes.items():
at.bind()
if at.instanced:
if instances is None:
instances = at.length
instanced_first_atname = atname
if instances != at.length:
raise ValueError((instanced_first_atname, instances), (atname, at.length))
else:
if length is None:
length = at.length
first_atname = atname
if length != at.length:
raise ValueError((first_atname, length), (atname, at.length))
if length is None:
length = 0
if self.instanced:
self.instances = instances
self.length = length
self.vao = vao
self.dirty = False
示例7: mainloop
def mainloop(self):
''' Starts the endless game loop '''
self.ping = time.time() + self.PING_INTERVAL
while True:
pkt = self.receive(blocking=False)
self.send()
# Check if brain is alive
if not threading.main_thread().is_alive():
self.log.info("Brain died, terminating")
break
# Send ping if needed
if self.lc and self.ping < time.time():
po = packets.PingPacket()
po.fill(0)
self.queue(po)
self.ping = time.time() + self.PING_INTERVAL
# Process packet
if pkt is None:
time.sleep(0.01)
else:
self.handlePacket(pkt)
示例8: _aenter
async def _aenter(self, daemon=False):
async with AsyncExitStack() as enter_stack:
if daemon and self._open_count == 0:
raise RuntimeError("The client is not active, first use of the client must not be daemon")
if self._shutdown:
raise RuntimeError("Cannot reuse a client after it was once shut down")
logger.debug("Entering as %s", "daemon" if daemon else "regular")
self._open_count += 1
@enter_stack.callback
def decrement_open_count():
self._open_count -= 1
if daemon:
self._daemon_count += 1
# testing: I see no good way to cause a fault that triggers this...
# the code is almost the same as decrement_open_count, so ignore it for coverage
@enter_stack.callback
def decrement_daemon_count():
self._daemon_count -= 1 # pragma: nocover
if self._open_count == 1:
logger.debug("Activating client...")
async with AsyncExitStack() as stack:
@asynccontextmanager
async def start() -> Component[None]:
component = await start_component(self.workload)
try:
yield component
finally:
await component.stop()
await stack.enter_async_context(start())
if threading.current_thread() is threading.main_thread():
loop = asyncio.get_event_loop()
def sigint_handler():
task = loop.create_task(self.shutdown())
# if this signal handler is called during _aenter, register the await with `stack`;
# otherwise, with `self._exit_stack`
exit_stack = self._exit_stack if self._exit_stack is not None else stack
@exit_stack.push_async_callback
async def await_shutdown():
await task
stack.enter_context(shutdown_handler.register_async(signal.SIGINT, sigint_handler))
# save the exit actions that need undoing...
self._exit_stack = stack.pop_all()
# ...and discard those that were only for the error case
enter_stack.pop_all()
logger.debug("Open: %d (%d daemon)", self._open_count, self._daemon_count)
return self
示例9: draw
def draw(self):
assert threading.current_thread() is threading.main_thread()
if self.dirty or not self.vao:
self.bind()
assert opengl_current_context() == self.context, "Cannot invoke Renderer from a different OpenGL context"
gl.glBindVertexArray(self.vao)
indexed = (self.indices is not None)
if self.command == "points":
mode = gl.GL_POINTS
elif self.command == "lines":
mode = gl.GL_LINES
elif self.command == "triangles":
mode = gl.GL_TRIANGLES
elif self.command == "triangle_strip":
mode = gl.GL_TRIANGLE_STRIP
elif self.command == "triangle_fan":
mode = gl.GL_TRIANGLE_FAN
else:
raise ValueError(self.command)
if not indexed:
if not self.instanced:
gl.glDrawArrays(mode, 0, self.length)
else:
gl.glDrawArraysInstanced(mode, 0, self.length, self.instances)
else:
if not self.instanced:
gl.glDrawElements(mode, self.indices.length,
self.indices.gl_dtype, ctypes.c_void_p(self.indices.offset))
else:
gl.glDrawElementsInstanced(mode, self.indices.length,
self.indices.gl_dtype, ctypes.c_void_p(self.indices.offset),
self.instances)
示例10: bind
def bind(self):
assert threading.current_thread() is threading.main_thread()
if self.length:
self.unbind()
if self.glsl_dtype == "vec4":
size, dtype = 4, gl.GL_FLOAT
elif self.glsl_dtype == "vec3":
size, dtype = 3, gl.GL_FLOAT
elif self.glsl_dtype == "vec2":
size, dtype = 2, gl.GL_FLOAT
elif self.glsl_dtype == "float":
size, dtype = 1, gl.GL_FLOAT
else:
raise TypeError(self.glsl_dtype)
self.verify_dtype()
self.store.bind()
offset = self.store.offset
stride = self.store.strides[0]
buf = self.store.opengl_id
loc = gl.glGetAttribLocation(self.shader_program, self.attribute)
if loc == -1:
print("WARNING: unused attribute '%s'" % self.attribute)
self.enabled = False
else:
gl.glEnableVertexAttribArray(loc)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf)
gl.glVertexAttribPointer(loc, size, dtype, False, stride, ctypes.c_void_p(offset))
if self.instanced:
gl.glVertexAttribDivisor(loc,1)
self.enabled = True
self.length = self.store.shape[0]
示例11: _init_scn
def _init_scn():
""" initialize once and only in mainthread """
global _is_init_already
if not _is_init_already and threading.current_thread() == threading.main_thread():
_is_init_already = True
logging.basicConfig(level=loglevel_converter(config.default_loglevel), format=config.logformat)
signal.signal(signal.SIGINT, _signal_handler)
示例12: remove_heart_log
def remove_heart_log(*args, **kwargs):
if six.PY2:
if threading.current_thread().name == 'MainThread':
debug_log(*args, **kwargs)
else:
if threading.current_thread() == threading.main_thread():
debug_log(*args, **kwargs)
示例13: _timeout_context
def _timeout_context(seconds, exception):
"""Timeout context manager that works in parent or child thread"""
if seconds is None or seconds <= 0: # pylint: disable=no-else-return
return _noop()
elif threading.current_thread() == threading.main_thread():
return _timeout_context_main(seconds, exception)
else:
return _timeout_context_child(seconds, exception)
示例14: is_main_thread
def is_main_thread():
"""
Return True if the current thread is the main thread.
"""
if sys.version_info[0] >= 3:
return threading.current_thread() == threading.main_thread()
else:
return isinstance(threading.current_thread(), threading._MainThread)
示例15: __check_bot_id
def __check_bot_id(self, name: str):
res = re.fullmatch(r'([0-9a-zA-Z\-]+)(\.[0-9]+)?', name)
if res:
if not(res.group(2) and threading.current_thread() == threading.main_thread()):
return name, res.group(1), res.group(2)[1:] if res.group(2) else None
self.__log_buffer.append(('error',
"Invalid bot id, must match '"
r"[^0-9a-zA-Z\-]+'."))
self.stop()