Python线程同时执行

2024-04-19 23:40:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个示例代码:

# some imports that I'm not including in the question

class daemon:
    def start(self):
        # do something, I'm not including what this script does to not write useless code to the question
        self.run()

    def run(self):
        """You should override this method when you subclass Daemon.

        It will be called after the process has been daemonized by 
        start() or restart().
        """

class MyDaemon(daemon):
    def run(self):
        while True:
            time.sleep(1)

if __name__ == "__main__":
    daemonz = MyDaemon('/tmp/daemon-example.pid')
    daemonz.start()

def firstfunction():
    # do something
    secondfunction()

def secondfunction():
    # do something
    thirdfunction()

def thirdfunction():
    # do something

# here are some variables set that I am not writing
firstfunction()

如何从类“daemon”的run(self)函数中退出并继续执行firstfunction(),就像在最后一行中所写的那样?我是Python的新手,我正在努力学习

#编辑 我设法将daemon类实现到treading类中。但我的情况与第一个相同,脚本保持在daemon类中,不执行其他行。在

^{pr2}$

Tags: therunselfthatdefnotsomedo
1条回答
网友
1楼 · 发布于 2024-04-19 23:40:14

您可以使用break关键字退出循环,然后继续下一行。return可用于退出函数。在

class daemon:
    def start(self):
        self.run()

    def run(self):
        while True:
            break
        return
        print()  # This never executes

如果希望MyDaemon与其余代码一起运行,则必须使其成为进程或线程。当MyDaemon类(线程/进程)运行时,代码自动继续到下一行。在

^{pr2}$

此代码生成以下结果:

Thread started
MyFunction executed

要使thread成为守护程序,可以使用thread.setDaemon(True)。必须在启动线程之前调用该函数:

thread = MyThread()
thread.setDaemon(True)
thread.start()
my_function()

相关问题 更多 >