Python - 线程 - 同时执行

时间:2017-07-19 23:32:52

标签: python python-3.x class object

我有这个示例代码:

# 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()

如何从类“守护进程”的run(self)函数退出并继续执行最后一行写的firstfunction()?我是Python的新手,我正在努力学习

#编辑 我设法将守护进程类实现到了treading类中。但是我的情况与第一种情况相同,脚本停留在守护进程类中并且不执行其他行。

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def daemonize(self):
    # istructions to daemonize my script process

    def run(self):
        self.daemonize()


def my_function():
    print("MyFunction executed") # never executed

thread = MyThread()
thread.start()
my_function() # the process is successfully damonized but
              # this function is never executed

1 个答案:

答案 0 :(得分:1)

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

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

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

如果您希望MyDaemon与其余代码一起运行,则必须将其作为进程或线程。然后代码自动继续到下一行,而MyDaemon类(线程/进程)运行。

import threading  


class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        print("Thread started")
        while True:
            pass


def my_function():
    print("MyFunction executed")

thread = MyThread()
thread.start()        # executes run(self)
my_function()

此代码产生以下结果:

Thread started
MyFunction executed

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

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