How to avoid race condition here

Will there be a race condition in getUrl if I run this using threads? I am changing the value of data['key'] in multiple threads. I need to pass the entire data to the request I make, basically, a set of keys will be fixed, only the key named key will change for each threaded call I make

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, '', i))

Thread Safety in Python’s dictionary I checked this, but my confusion is will the thread switch context the moment I do a set in data['key'] = value and then some other thread changes that and the next line now has the new value set by a different thread.


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`

If I use locks then I will lose the concurrency here.


Your current code has indeed a race condition because you are changing and using a same global variable in different threads. A simple way would be to use a local copy:

def getUrl(url, value):
    data2 = dict(data, 'key' = value)         # build a local instance
    return requests.get(url, data=data2).text # and use it: no race condition