How to go about. On read/write locks

Diez B. Roggisch deets at nospam.web.de
Mon Apr 6 08:49:23 CEST 2009


Emanuele D'Arrigo schrieb:
> Hi everybody,
> 
> I'm having a threading-related design issue and I suspect it has a
> name that I just don't know.  Here's a description.
> 
> Let's assume a resource (i.e. a dictionary) that needs to be accessed
> by multiple threads. A simple lock will do the job but in some
> circumstances it will create an unnecessary bottleneck. I.e. let's
> assume that most threads only need to have a -read- access to the
> resource, while only few threads actually change the dictionary.
> Ideally, the reading threads should not block each other. However, as
> soon as a threads intends to change the dictionary it should let all
> the reading threads finish, lock the access to the resource, change
> it, and then release the lock.
> 
> I don't think it'd be difficult to implement but I'm wondering if
> something in this direction has been done already, if it has a name or
> if it's even well known design pattern.
> 
> Anybody can shed some light?


There are two answers to this - the general, and the CPython-specific.

The general is this: if you need reading to finish before you write, you 
need a lock that guards every access to the dict. There is no "cheap to 
obtain but only effective for some threads"-lock.


The CPython-specific answer is that the GIL takes care of that for you 
right now anyway. So unless you plan for a distant future where some 
kind of swallows fly around that don't have a GIL, you are safe to 
simply read and write in threads without any locking whatsoever.

Diez



More information about the Python-list mailing list