為什么 getattr 不起作用?我不是要為 threadLocal 設定默認值,我想知道為什么 getattr 不能按我希望的方式作業?試圖鎖定,相同的輸出
預期產出
0
1
2
3
4
main thread
電流輸出
0
0
0
0
0
main thread
代碼
from concurrent.futures import ThreadPoolExecutor
from threading import local
threadLocal = local()
threadLocal.x = 'main thread'
def f(x):
# threadLocal.x = x # this works
threadLocal.x = getattr(threadLocal, 'x', x) # this does not work
return threadLocal.x
pool = ThreadPoolExecutor(5)
result = pool.map(f, range(0, 5))
for i in result:
print(i)
print(threadLocal.x)
uj5u.com熱心網友回復:
執行緒池在作業項之間共享其作業執行緒。這意味著如果一個作業項在下一個之前完成,兩者都可以在同一個執行緒上運行,從而看到相同的執行緒區域變數。
這正是這里發生的情況:由于f執行速度非常快,大多數或所有作業項都在第一個作業執行緒中運行。第一個任務f(0)設定threadLocal.x = 0在這里,其他任務運行在同一個執行緒中,因此讀取threadLocal.x = 0.
您可以通過(人為)增加f.
def f(x):
time.sleep(0.2) # delay for other work items to start running
threadLocal.x = getattr(threadLocal, 'x', x) # this works now
return threadLocal.x
請注意,任何額外的操作可能足以打破計時問題:例如,包括print引數和執行緒本地。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359336.html
