【发布时间】:2019-07-13 15:32:18
【问题描述】:
我正在尝试使用 concurrent.futures.ThreadPoolExecutor 模块来并行运行类方法,我的代码的简化版本几乎如下:
class TestClass:
def __init__(self, secondsToSleepFor):
self.secondsToSleepFor = secondsToSleepFor
def testMethodToExecInParallel(self):
print("ThreadName: " + threading.currentThread().getName())
print(threading.currentThread().getName() + " is sleeping for " + str(self.secondsToSleepFor) + " seconds")
time.sleep(self.secondsToSleepFor)
print(threading.currentThread().getName() + " has finished!!")
with concurrent.futures.ThreadPoolExecutor(max_workers = 2) as executor:
futuresList = []
print("before try")
try:
testClass = TestClass(3)
future = executor.submit(testClass.testMethodToExecInParallel)
futuresList.append(future)
except Exception as exc:
print('Exception generated: %s' % exc)
如果我执行此代码,它的行为似乎与预期的一样。 但是如果我犯了一个错误,比如在“testMethodToExecInParallel”中指定了错误数量的参数,比如:
def testMethodToExecInParallel(self, secondsToSleepFor):
然后仍然提交函数为:
future = executor.submit(testClass.testMethodToExecInParallel)
或尝试在“testMethodToExecInParallel”方法的打印语句中将字符串对象与整数对象连接(不使用 str(.) ):
def testMethodToExecInParallel(self):
print("ThreadName: " + threading.currentThread().getName())
print("self.secondsToSleepFor: " + self.secondsToSleepFor) <-- Should report an Error here
程序不返回任何错误;只是打印“尝试前”并结束执行...
理解这使得程序几乎无法调试是微不足道的......有人可以解释一下为什么会发生这种行为吗?
(对于第一种错误)concurrent.futures.ThreadPoolExecutor 不检查具有指定签名的函数以提交,并最终抛出某种“noSuchFunction”异常?
也许在提交到 ThreadPoolExecutor 类方法而不是简单的独立函数时会出现某种问题,因此,这种行为是可以预期的?
或者错误是在线程内部抛出的,由于某种原因我无法阅读?
-- 编辑--
Akshay.N 建议在向 ThreadPoolExecutor 提交函数后插入 future.result() 使程序按预期运行:如果代码正确则运行良好,如果代码中有错误则打印错误。
必须警告用户注意 ThreadPoolExecutor 的这种非常奇怪的行为: 如果您只向 ThreadPoolExecutor 不调用 future.result() 提交函数: - 如果代码正确,则程序继续运行并按预期运行 - 如果代码中的某些错误似乎程序没有调用提交的函数,不管它做什么:它不会报告代码中的错误
【问题讨论】:
标签: python python-3.x multithreading concurrent.futures