【问题标题】:How can I run a same function multiple times, parallel in python?如何在 python 中并行运行同一个函数多次?
【发布时间】:2019-11-23 08:54:44
【问题描述】:

我有一个只有一个功能的程序。代码的基本原理是询问用户是否要继续添加值或停止。如果是,则要求添加值的函数将被多次调用,这也是并行的,因此执行也将是并行的。以伪代码的方式,

def func1():
a = input("Enter value" )
do something with a

b = input("would you like to add more values?" )
if b == "Y"
func1()
else
exit()

但这不是平行的。它将等待第一个函数完全结束。我知道我必须在这里使用多处理。但是如何解决确切的问题,我想不通。感谢您的帮助...

【问题讨论】:

标签: python-3.x python-multiprocessing python-multithreading


【解决方案1】:

我不认为你真的需要在这里使用多处理,你可以在一个基本的 while 循环中这样做:

value = 0

while True:
    a = input("Enter value: ")
    value += int(a)

    b = input("would you like to add more values? ")
    if b == "Y" or b == "y":
        pass
    else:
        break

print("The value: " + str(value))

那么程序就会这样工作:

$ python test.py
Enter value: 345673
would you like to add more values? y
Enter value: 43563
would you like to add more values? y
Enter value: 546734
would you like to add more values? n
The value: 935970

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    相关资源
    最近更新 更多