On Thu, May 31, 2007 at 11:51:27AM +0100, Brian Candler wrote:
> > The reason for using synchronization in #search is because we might
> > start in the middle of a #write call from another thread, right? I had
> > something in mind like an SQL database which would search using the
> > "not-yet-written" version of the data... but now I think I see that's
> > quite complicated.
> 
> No, that's quite doable as well. What you need to do is to protect the part
> where you replace @data with new_data, to ensure there are no readers of
> @data while you're changing it.

Hmm, the code I gave didn't actually do this :-) But it did allow multiple
readers while there are no changes taking place.

Considering alternatives reveals some of the pitfalls. For example, you can
conceive of a strategy where the update thread does the following:

1. grabs a shared read lock
2. makes a local copy of the data and modifies it
3. upgrades its lock to exclusive
4. replaces the stored data with its modified copy
5. drops its lock

However this fails totally if two update threads come along at the same
time. They both successfully grab the read lock, both make their local
modifications, and then both hang forever waiting to get an exclusive lock,
which they can't do while the other still holds a read lock. This is known
as a "deadlock" scenario.

This is where a good book comes in. There are some relevant articles on
wikipedia. Googling for "philosophers" and "spaghetti" may also be helpful
:-)

Regards,

Brian.