threads: not locking read-only objects

Jon Perez jbperez808 at wahoo.com
Fri Aug 6 22:58:09 EDT 2004


Hmmm... here's what's going on.  I have a dictionary of
logged in users called 'whoison' that's updated in the main
thread (and only in the main thread) with a:

whoison['username']="timeoflogin"  # to add someone new

and

del whoison['username']  # to remove someone who's logged out


Do the above count as atomic?


The worker threads do the following read-only operation:

for x in whoison:
   print x,whoison[x]

Looking at the read-only code though I just realized
something.... if a dictionary entry in 'whoison' is deleted
by the main thread while the 'for x in whoison' is executing
then what would happen?

Looks like I'm going to need a lock after all even for the
read-only operations...?



Christopher T King wrote:

> On Sat, 7 Aug 2004, Jon Perez wrote:
> 
> 
>>Is it safe to not put a lock on an object if it will always
>>be read-only in other threads and will only ever be written to
>>in just one and always the same one thread?
> 
> 
> Only if the writes are guaranteed to be atomic: if the object is ever 
> temporarily left in an inconsistent state by the writer (due to a thread 
> switch), the readers will read inconsistent data.  If you are sure this 
> can't happen, then yes, doing so is safe.
> 



More information about the Python-list mailing list