簡體   English   中英

python線程本地意外值

[英]python threading local unexpected value

為什么 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)

線程在工作項之間共享其工作線程。 這意味着如果一個工作項在下一個之前完成,兩者都可以在同一個線程上運行,從而看到相同的線程局部變量。

這正是這里發生的情況:由於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參數和線程本地。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM