[Web-SIG] Threading and client-side support

amk at amk.ca amk at amk.ca
Mon Oct 27 10:07:09 EST 2003


On Mon, Oct 27, 2003 at 02:45:16PM +0000, John J Lee wrote:
> I suppose I should ask on python-dev if there's a policy / tradition here.

The rough tradition would be: Thread-safety is good, and library modules
shouldn't be non-threadsafe unless there's a very good reason.  

> changing?  I suppose I'd also need to just label the .cookies attribute as
> non-threadsafe (or get rid of it, or add a __getattr__ to allow locking it
> -- yuck). 

Assuming .cookies is a Python dictionary (I haven't looked at the CookieJar
code), there's no locking needed.  Locking is necessary when a data
structure is temporarily inconsistent, or some invariant is temporarily
broken.  

For example, let's say you had two dictionaries, .cookies which maps name ->
Cookie object, and .durations which maps name -> an integer given the
duration of the cookie, and it's stated that every entry in .cookies always
has a corresponding entry in .durations.  In this case you need locking,
because when you add an entry like this:

           self.cookies[name] = Cookie()
	   # danger point
	   self.durations[name] = value
	   
If a thread switch occurs at the danger point, another thread might loop
over cookies.items(), see the missing duration, and die with a KeyError, so
you need to have a lock around the two statements, and make read accesses
use the lock.  (You could also set the value in .durations first and avoid
locking, but that's not possible in general.)

But if you're assigning to a single attribute (self.filename = 'foo'),
there's no point in time where the attribute is inconsistent, a mix of the
old and new names; instead it's first the old value, and then it's set to
'foo'.  So no lock is needed.

--amk





More information about the Web-SIG mailing list