Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you make this Python Dictionary thread-safe?

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 ?

like image 255
BuZz Avatar asked Dec 13 '11 10:12

BuZz


2 Answers

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.

like image 172
Joonas Pulakka Avatar answered Oct 11 '22 07:10

Joonas Pulakka


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
like image 35
Andrew Wilkinson Avatar answered Oct 11 '22 06:10

Andrew Wilkinson