我想同时运行两个函数



我已经尝试了旧问题的所有解决方案,但情况就是这样......
函数 1 如下

def fun1():
subprocess("Something in there")

和功能2

def fun2():
fun_from_another_file()

跑步就像

def run():
p1 = Process(target=fun1)
p1.start()
p2 = Process(target=fun2)
p2.start()
p1.join()
p2.join()

它们应该一次运行,但第二个函数只有在第一个函数完成执行后才能工作......
请帮忙...
我是Python的新手

下面是一个包含更正的工作示例:

import time
from multiprocessing import Process
def fun1(): # need parentheses here to declare a no-parameter function
for i in range(5):
print(f'func1: {i}')
# multiprocessing starts up slow, so the first function could finish before
# The second processes is up and running.  Slow down a bit to see parallelism.
time.sleep(.1)
def fun2():  # need parentheses here
for i in range(5):
print(f'func2: {i}')
time.sleep(.1)
def run():  # need parentheses here
p1 = Process(target=fun1)
p1.start()
p2 = Process(target=fun2)
p2.start()  # need parentheses here to call the function.
p1.join()
p2.join()
# Required on some OSes for multiprocessing to work properly.
if __name__ == '__main__':
run() # need to actually call the run() function.

输出:

func1: 0
func2: 0
func1: 1
func2: 1
func1: 2
func2: 2
func1: 3
func2: 3
func1: 4
func2: 4

您尚未在p2上调用start。您刚刚访问了该函数而没有调用它,这将返回一个未在任何地方使用的函数对象。替换为p2.start()

相关内容

  • 没有找到相关文章

最新更新