Python:同时执行多个函数

编程入门 行业动态 更新时间:2024-10-26 02:35:31
本文介绍了Python:同时执行多个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在 Python 中同时运行两个函数.我已经尝试了以下使用 multiprocessing 的代码,但是当我执行代码时,第二个函数仅在第一个函数完成后才启动.

I'm trying to run two functions simultaneously in Python. I have tried the below code which uses multiprocessing but when I execute the code, the second function starts only after the first is done.

from multiprocessing import Process def func1: #does something def func2: #does something if __name__=='__main__': p1 = Process(target = func1) p1.start() p2 = Process(target = func2) p2.start()

推荐答案

您做得对.:)

尝试运行这段愚蠢的代码:

Try running this silly piece of code:

from multiprocessing import Process import sys rocket = 0 def func1(): global rocket print 'start func1' while rocket < sys.maxint: rocket += 1 print 'end func1' def func2(): global rocket print 'start func2' while rocket < sys.maxint: rocket += 1 print 'end func2' if __name__=='__main__': p1 = Process(target = func1) p1.start() p2 = Process(target = func2) p2.start()

您将看到它打印start func1",然后打印start func2",然后经过(非常)很长时间后,您将最终看到函数结束.但它们确实会同时执行.

You will see it print 'start func1' and then 'start func2' and then after a (very) long time you will finally see the functions end. But they will indeed execute simultaneously.

因为进程需要一段时间才能启动,您甚至可能会看到'start func2' before 'start func1'.

Because processes take a while to start up, you may even see 'start func2' before 'start func1'.

更多推荐

Python:同时执行多个函数

本文发布于:2023-06-06 09:45:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/539018.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   函数   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!