如何在python的不同线程中运行两个或三个不同的函数?
例如,如果我创建了一些示例函数,如下所示。
def method1(x,y):
calc = x*y
print(calc)
def method2(x,y):
calc = x+y
print(calc)
def method3(x,y):
calc = x-y
print(calc)
我将如何在不同线程中同时运行所有三个功能?
使用ThreadPoolExecutor
的示例(在Python3中可用)
from concurrent.futures import ThreadPoolExecutor
def method1(x,y):
calc = x*y
print(calc)
def method2(x,y):
calc = x+y
print(calc)
def method3(x,y):
calc = x-y
print(calc)
pool = ThreadPoolExecutor(max_workers=3)
x = 5
y = 6
pool.submit(method1, x, y)
pool.submit(method2, x, y)
pool.submit(method3, x, y)