如何使用线程函数在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学习者快速成长!