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

Barbara Streisand
發布: 2024-10-25 08:09:28
原創
770 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!