【发布时间】:2021-09-21 07:13:38
【问题描述】:
如果我使用线程运行它,getUrl 中是否会有竞争条件?我正在多个线程中更改data['key'] 的值。我需要将整个data 传递给我提出的请求,基本上,一组键将被固定,只有名为key 的键会因我发出的每个线程调用而改变
import requests
from concurrent.futures import ThreadPoolExecutor
def getUrl(url, value):
data['key'] = value # will there be a race condition here
return requests.get(url, data=data).text # and when the value is passed here
data = {'key': 1, 'fixedKey': 'fixedValue', 'fixedKey2': 'fixedValue2'}
resultArray = []
threadPool = ThreadPoolExecutor(32)
for i in range(100):
resultArray.append(threadPool.submit(getUrl, 'https://google.com', i))
Thread Safety in Python's dictionary 我检查了这个,但我的困惑是当我在data['key'] = value 中进行设置时线程切换上下文,然后其他一些线程更改了它,下一行现在具有由不同线程设置的新值.
例子
Value set by thread 1
data['key'] = 1
Context Switch
Value set by thread 2
data['key'] = 2
Context Switch back to old thread 1
is data['key'] = `2` now? I would necessarily want the value `1`
如果我使用锁,那么我将在这里失去并发性。
【问题讨论】:
-
为什么要更改函数内部的值?为什么不在 for 循环本身@Jake 中做呢?
-
如果我错了请纠正我,我不能 100% 确定所有函数调用是否会在执行后使用不同的值@Vishnudev
-
他们可能会,他们可能不会。取决于很多事情。为了确保它们不使用更改的值,请尝试在函数之外进行。
标签: python