簡體   English   中英

Python-線程處理-同時執行

[英]Python - Threading - execute simultaneously

我有以下示例代碼:

# 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的新手,我正在嘗試學習

#EDIT我設法將守護程序類實現為踩踏類。 但首先我處於相同的情況,腳本保留在daemon類中,不執行其他行。

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

您可以使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM