多线程:如何在不同的线程中运行不同的功能?

问题描述 投票:1回答:1

如何在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)

我将如何在不同线程中同时运行所有三个功能?

python python-3.x multithreading python-multithreading
1个回答
0
投票

使用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)
© www.soinside.com 2019 - 2024. All rights reserved.