首頁  >  文章  >  後端開發  >  如何使用線程函數在Python腳本中同時執行兩個函數?

如何使用線程函數在Python腳本中同時執行兩個函數?

Barbara Streisand
Barbara Streisand原創
2024-10-25 08:09:28762瀏覽

How to execute two functions concurrently in a Python script using a threaded function?

在Python 中建立執行緒

問題:
如何在Python 腳本中同時執行兩個函數使用線程函數而不是類別?

工作腳本:

<code class="python">from threading import Thread

class myClass():

    def help(self):
        os.system('./ssh.py')

    def nope(self):
        a = [1,2,3,4,5,6,67,78]
        for i in a:
            print(i)
            sleep(1)


if __name__ == "__main__":
    Yep = myClass()
    thread = Thread(target=Yep.help)
    thread2 = Thread(target=Yep.nope)
    thread.start()
    thread2.start()
    thread.join()
    print('Finished')</code>

改進的解決方案:

<code class="python">from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print("running")
        sleep(1)


if __name__ == "__main__":
    thread = Thread(target=threaded_function, args=(10,))
    thread.start()
    thread.join()
    print("thread finished...exiting")</code>

>說明說明🎜>

此改進的腳本示範如何透過將目標函數和任何必要的參數傳遞給Thread 建構子來直接建立線程,而不是使用線程類別。 target 參數指定要在單獨執行緒中執行的函數。在這種情況下,threaded_function() 函數與主執行緒同時呼叫。 join() 方法確保主執行緒等待執行緒完成後再繼續執行。

以上是如何使用線程函數在Python腳本中同時執行兩個函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn