我有一个Python脚本和一个简单的函数。我想同时运行这个函数2次,想知道这是否可能。
script.py:
from multiprocessing import Process
import time
def func1():
time.sleep(1)
print('Finished sleeping')
t1_start = time.perf_counter()
p1 = Process(target=func1())
p1 = Process(target=func1())
t1_stop = time.perf_counter()
print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))
给定输出:
Finished sleeping
Finished sleeping
elapsed time: 2 sec
预期输出:Finished sleeping
Finished sleeping
elapsed time: 1 sec
我也试过这个:
from multiprocessing import Process
import time
def func1():
time.sleep(1)
print('Finished sleeping')
if __name__ == '__main__':
t1_start = time.perf_counter()
p1 = Process(target=func1) # note no ()
p2 = Process(target=func1) # note no ()
p1.start()
p2.start()
t1_stop = time.perf_counter()
print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))
然而,这给出了这样的输出:
elapsed time: 0 sec
Finished sleeping
Finished sleeping
-
target=func1()
调用func1
并传递其返回值(在本例中为None
)作为Process
的目标参数,而不是传递函数func1
本身。 -
Process(...)
只是创建一个Process
对象。您从未真正生成/执行任何已创建的Process
对象。您需要添加对.start
的呼叫。这取决于操作系统(例如,如果使用os.fork
来生成新进程),这还需要我们添加__main__
保护(无论使用哪种操作系统,这都是最佳实践)。 -
您使用了两次
p1
。
试试这个:
from multiprocessing import Process
import time
def func1():
time.sleep(1)
print('Finished sleeping')
if __name__ == '__main__':
t1_start = time.perf_counter()
p1 = Process(target=func1) # note no ()
p2 = Process(target=func1) # note no ()
p1.start()
p2.start()
t1_stop = time.perf_counter()
print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))
输出
elapsed time: 0 sec
Finished sleepingFinished sleeping
是有意义的。如果这个函数在不同的进程中执行了2次,那么主进程根本不会执行time.sleep(1)
。
但是,如果我们添加.join()
,那么主进程将被迫等待子进程:
p1.start()
p2.start()
p1.join()
p2.join()
现在输出与您需要的输出相同:
Finished sleeping
Finished sleeping
elapsed time: 1 sec
编辑:如果你想要一个任意数量的进程的循环:
...
times = 3
processes = []
for _ in range(times):
p = Process(target=func1)
p.start()
processes.append(p)
for p in processes:
p.join()
...