繁体   English   中英

我想同时运行两个函数

[英]I want to run two functions at same time

我已经尝试了旧问题的所有解决方案,但情况就是这样......
函数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()

它们应该一次运行,但第二个 function 只有在第一个 function 完成执行后才能工作......
请帮忙...
我是 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.

Output:

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

您还没有在p2上调用start 您刚刚访问了 function 而不调用它,它返回一个未在任何地方使用的 function object。 替换为p2.start()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM