所以我在下面的代码中遇到了奇怪的行为。我在分配之前引用了局部变量flag
时出错,但是在顶部将其分配为全局变量。有人可以告诉我这里发生了什么,为什么flag
没有按预期增加?
import concurrent.futures
flag = 0
def make_some():
try:
flag += 1
except Exception as e:
print(e)
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
tasks = {
executor.submit(
make_some
): task_id
for task_id in [1,2,3]
}
for future in concurrent.futures.as_completed(tasks):
pass
您必须使用global关键字来解决此问题
在此处阅读更多https://www.tutorialspoint.com/global-keyword-in-python
因此,如果没有global,则每个变量都只在局部范围内,就好像没有定义全局变量一样,因此会出现错误
一旦使用global关键字,然后在内部作用域中python确认存在global变量定义
这应该起作用(添加global
):
import concurrent.futures
flag = 0
def make_some():
global flag # <--- USE GLOBAL
try:
flag += 1
except Exception as e:
print(e)
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
tasks = {
executor.submit(
make_some
): task_id
for task_id in [1,2,3]
}
for future in concurrent.futures.as_completed(tasks):
pass