ThreadPoolExecutor未定义[python3]
我正在尝试运行以下代码,这段代码是直接从文档中复制过来的:https://docs.python.org/dev/library/concurrent.futures.html#module-concurrent.futures:
import executor
import concurrent.futures
import time
def wait_on_b():
time.sleep(5)
print(b.result()) # b will never complete because it is waiting on a.
return 5
def wait_on_a():
time.sleep(5)
print(a.result()) # a will never complete because it is waiting on b.
return 6
executor = ThreadPoolExecutor(max_workers=2)
a = executor.submit(wait_on_b)
b = executor.submit(wait_on_a)
然后我得到了以下输出:
Traceback (most recent call last):
File "test1.py", line 16, in <module>
executor = ThreadPoolExecutor(max_workers=2)
NameError: name 'ThreadPoolExecutor' is not defined
我在想可能是我忘记导入某些东西,但我不知道具体是什么。
1 个回答
7
你可以选择用 from concurrent.futures import ThreadPoolExecutor
来代替 import concurrent.futures
,或者保持原来的导入方式,然后使用 executor = concurrent.futures.ThreadPoolExecutor(maxworkers=2)
。
另外要注意,你复制的示例代码是故意设计成会死锁的,所以即使你解决了导入的问题,它也不会正常工作。