• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python threading.main_thread函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中threading.main_thread函数的典型用法代码示例。如果您正苦于以下问题:Python main_thread函数的具体用法?Python main_thread怎么用?Python main_thread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了main_thread函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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")
开发者ID:purduesigbots,项目名称:JINX,代码行数:27,代码来源:JINX.py


示例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()
开发者ID:hugobuddel,项目名称:orange3,代码行数:15,代码来源:lazytable.py


示例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)
开发者ID:CenterForOpenScience,项目名称:SHARE,代码行数:30,代码来源:jobs.py


示例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
开发者ID:Siecje,项目名称:asphalt,代码行数:33,代码来源:util.py


示例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' })
开发者ID:dropmann,项目名称:silky,代码行数:33,代码来源:enginemanager.py


示例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
开发者ID:agoose77,项目名称:seamless,代码行数:32,代码来源:Renderer.py


示例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)
开发者ID:gtozzi,项目名称:pyuo,代码行数:25,代码来源:client.py


示例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
开发者ID:PRIArobotics,项目名称:HedgehogClient,代码行数:60,代码来源:async_client.py


示例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)
开发者ID:sjdv1982,项目名称:seamless,代码行数:32,代码来源:Renderer.py


示例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]
开发者ID:sjdv1982,项目名称:seamless,代码行数:31,代码来源:Renderer.py


示例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)
开发者ID:kikiyou,项目名称:simplescn,代码行数:7,代码来源:__main__.py


示例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)
开发者ID:lstwzd,项目名称:easytrader,代码行数:7,代码来源:sinamonitrader.py


示例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)
开发者ID:egtaonline,项目名称:GameAnalysis,代码行数:8,代码来源:utils.py


示例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)
开发者ID:spacetelescope,项目名称:asv,代码行数:8,代码来源:util.py


示例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()
开发者ID:certtools,项目名称:intelmq,代码行数:9,代码来源:bot.py


示例16: is_main

    def is_main(self, thread=None):
        """Check if the thread is the main thread.

        thread - the thread to check. Use current thread if not provided.
        """
        if not thread:
            thread = self.current()
        with self.lock:
            return thread is self.pool[threading.main_thread()][-1]
开发者ID:eight04,项目名称:pyWorker,代码行数:9,代码来源:__init__.py


示例17: run

	def run(self):	#this function is called when the bot starts, it does error detection and stuff
		self.thread_connect.start()
		self.thread_handle.start()
		self.thread_detectTimeout.start()
		#self.thread_consInp.start()
		while not self.stop:
			try:
				if self.breakstuff:
					self.breakstuff = False
					raise I_like_trains
				if self.brokenPipe != False or self.pingTimeout != False:
					self.echo("Broken Pipe: {}".format(self.brokenPipe), "warn")
					self.echo("PingTimeout: {}".format(self.pingTimeout), "warn")
					self.echo("exiting...", "warn")
					self.exit()
					self.echo("reconnecting in 10 seconds")
					time.sleep(4)
				if self.stop == True:
					break
				time.sleep(0.42)

			except Exception as e:
				self.echo(traceback.format_exc(), "warn")
				time.sleep(4)
				return

		self.echo("waiting for threads to stop...")

		for t in threading.enumerate():
			try:
				omitted = False
				if t.ident == None:
					omitted = "not started"
				elif t == threading.main_thread():
					omitted = "main thread"
				elif t == threading.current_thread():
					omitted = "current thread"
				elif t.daemon:
					omitted = "daemon"

				if omitted:
					self.echo("omitted {omitted} thread {thread}".format(thread=t.name, omitted=omitted))
				else:
					self.echo("joining thread {thread}".format(thread=t.name))
					t.join(5)
					if t.is_alive():
						self.echo("thread {thread} did not exit within 5 seconds!".format(thread=t.name))
					else:
						self.echo("thread {thread} exited!".format(thread=t.name))
			except:
				self.echo(traceback.format_exc(), "warn")

		self.echo("all threads stopped!")
		self.echo("exiting in 2 seconds")
		time.sleep(2)
		Echo.end(self.screen)
		return
开发者ID:DigitalChiller,项目名称:ircbot,代码行数:57,代码来源:IRC.py


示例18: run_with_lock

    def run_with_lock(*args, **kwargs):
        with blivet_lock:
            if current_thread() == main_thread():
                exn_info = get_thread_exception()
                if exn_info[1]:
                    clear_thread_exception()
                    raise ThreadError("raising queued exception") from exn_info[1]

            return m(*args, **kwargs)
开发者ID:afamilyman,项目名称:blivet,代码行数:9,代码来源:threads.py


示例19: new_event_loop

    def new_event_loop(self):
        """Create a new event loop and return it."""
        if not self._default_loop and threading.current_thread() == threading.main_thread():
            loop = self.get_default_loop()
        else:
            loop = CFEventLoop(self._lifecycle)
        loop._policy = self

        return loop
开发者ID:pybee,项目名称:rubicon-objc,代码行数:9,代码来源:eventloop.py


示例20: pause_all

    def pause_all(self):
        if threading.active_count() == 1:
            return
#        ok = QMessageBox.question(self, '注意', '所有正在下载任务将被暂停,您是否继续?', QMessageBox.No|QMessageBox.Yes, QMessageBox.No)
#        if ok == QMessageBox.Yes:
        for t in threading.enumerate():
            if t.name == "downloadLrc" or t.name == "volumeThread" or t == threading.main_thread():
                continue
            t.pause()
开发者ID:xuhuairuogu,项目名称:xyplayer-package,代码行数:9,代码来源:mywidgets.py



注:本文中的threading.main_thread函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python threading.setprofile函数代码示例发布时间:2022-05-27
下一篇:
Python threading.lock函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap