I have a Web Server running in Python
. The server is private, so i only expect around 20 users to connect to it. The server is multi-threaded (8 cores at the moment, so 8 threads I guessed).
When requests come in, I am able to identify the users. On some queries, I need to update a simple dictionary
of the form username -> Boolean. How could I make this one thread safe ?
You may or may not need to use a lock, depending on how the Boolean
is updated.
If the value of the Boolean
doesn't depend on its previous value, then no lock is needed: writing and reading a Python dictionary is thread-safe by itself (except: writing while iterating is not allowed - but that's not allowed in single thread either). The memory visibility is similar to what would be achieved using volatile
in some languages.
What's inherently not thread-safe is the "read-modify-write" -sequence, resulting in a race condition. If the value of the Boolean
does depend on its previous value, then you have to use a lock, because otherwise thread A could first read the value, then thread B could change it, and then A would change it again, based on outdated value to start with.
You'll need to create a global lock object.
lock = threading.Lock()
Then around each access of the dictionary acquire and release the lock. The simplest way to do this is with the new(ish) with
syntax.
with lock:
dict[key] = value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With