Python:同时执行多个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18864859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:05:42  来源:igfitidea点击:

Python: Executing multiple functions simultaneously

python

提问by user2739601

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

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

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()

采纳答案by Shashank

You are doing it correctly. :)

你做得对。:)

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()

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 func1”,然后打印“start func2”,然后在(非常)很长时间后,您将最终看到函数结束。但它们确实会同时执行。

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

由于进程需要一段时间才能启动,您甚至可能会“start func1”之前看到“start func2 ”。

回答by Alistair Bendall

This is just what i needed. I know it wasn't asked but i modified shashank's code to suit Python 3 for anyone else looking :)

这正是我所需要的。我知道它没有被问到,但我修改了 shashank 的代码以适合 Python 3 以供其他人查找:)

from multiprocessing import Process
import sys

rocket = 0

def func1():
    global rocket
    print ('start func1')
    while rocket < sys.maxsize:
        rocket += 1
    print ('end func1')

def func2():
    global rocket
    print ('start func2')
    while rocket < sys.maxsize:
        rocket += 1
    print ('end func2')

if __name__=='__main__':
    p1 = Process(target=func1)
    p1.start()
    p2 = Process(target=func2)
    p2.start()

Substitute sys.maxsize for an number then print(rocket)and you can see it count up one at a time. Get to a number and stop

将 sys.maxsize 替换为一个数字,然后打印(火箭),您可以看到它一次计数一个。到达一个数字并停止

回答by TheWalkingData

This is a very good example by @Shashank. I just want to say that I had to add joinat the end, or else the two processes were not running simultaneously:

这是@Shashank 的一个很好的例子。我只想说join最后必须加上,不然两个进程不是同时运行的:

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()
    # This is where I had to add the join() function.
    p1.join()
    p2.join()

Furthermore, Check this thread out: When to call .join() on a process?

此外,请查看此线程: 何时在进程上调用 .join()?

回答by Ahmed Benhida

Here is another version, if a dynamic list of processes need to be run. I am including the two shell scripts, if you want to try it:

这是另一个版本,如果需要运行进程的动态列表。如果您想尝试一下,我将包含两个 shell 脚本:

t1.sh

t1.sh

for i in {1..10}
  do 
     echo "1... t.sh i:"$i
     sleep 1
  done

t2.sh

t2.sh

   for i in {1..3}
   do
       echo "2.. t2.sh i:"$i
       sleep 1
   done

np.py

压缩包

import os
from multiprocessing import Process, Lock

def f(l, cmd):
    os.system(cmd)

if __name__ == '__main__':
    lock = Lock()

    for cmd in ['sh t1.sh', 'sh t2.sh']:
        Process(target=f, args=(lock, cmd)).start()

output

输出

1... t.sh i:1
2.. t2.sh i:1
1... t.sh i:2
2.. t2.sh i:2
1... t.sh i:3
2.. t2.sh i:3
1... t.sh i:4
1... t.sh i:5
1... t.sh i:6
1... t.sh i:7
1... t.sh i:8
1... t.sh i:9
1... t.sh i:10

"lock" left there can be acquired before task "l.acquire()" and released after "l.release()"

留在那里的“锁”可以在任务“ l.acquire()”之前获取并在“ l.release()”之后释放

回答by Ion Stoica

This can be done elegantly with Ray, a system that allows you to easily parallelize and distribute your Python code.

这可以通过Ray优雅地完成,这是一个允许您轻松并行化和分发 Python 代码的系统。

To parallelize your example, you'd need to define your functions with the @ray.remote decorator, and then invoke them with .remote.

要并行化您的示例,您需要使用 定义函数@ray.remote decorator,然后使用 调用它们.remote

import ray

ray.init()

# Define functions you want to execute in parallel using 
# the ray.remote decorator.
@ray.remote
def func1():
    #does something

@ray.remote
def func2():
    #does something

# Execute func1 and func2 in parallel.
ray.get([func1.remote(), func2.remote()])

If func1()and func2()return results, you need to rewrite the code as follows:

如果func1()func2()返回结果,则需要将代码改写如下:

ret_id1 = func1.remote()
ret_id2 = func1.remote()
ret1, ret2 = ray.get([ret_id1, ret_id2])

There are a number of advantages of using Ray over the multiprocessingmodule. In particular, the same codewill run on a single machine as well as on a cluster of machines. For more advantages of Ray see this related post.

多处理模块相比,使用 Ray 有许多优点。特别是,相同的代码将在单台机器和机器集群上运行。有关 Ray 的更多优势,请参阅此相关帖子