Locking Multiple Objects

There are times when I wish pthreads had a two-pass read/write mutex. I guess I should be happy that it's got the read/write mutex and I can make something like a two-pass lock with retries. Basically, if I want to lock n objects in C++ using pthread mutexes, I have to try_lock the first one, if it fails, optionally wait a bit and try again. If it succeeds, then I can try the next one, and if it fails, back out the ones I've received, otherwise try the next one, etc. This scheme is nice in that it allows me to make the functionality I need, but it'd be great if pthreads had the ability to prepare_to_lock and then lock so you could make the two-pass system that would make it possible to make sure you could get everything you needed before locking anything up. My solution locks and unlocks, which can be a waste if one of the objects is write-locked, for instance.

But I suppose the fact that I can get most of what I want with a very little bit of code is nice. But it'd be great if they added that. Or maybe BOOST could make that out of other primitives.

The reason for this is that you get deadlocks when you try to lock multiple objects in a single, atomic unit, and that's what's been happening in my code. I have one section where a family of objects are locked for read, and another where a similar set are locked for writing. The problem I've hit is that the timing of the multiple threads in the system is very hard to pin down, and I don't want to use exclusive locks (mutexes) which would make things a lot easier, but would lock more than I want, and slow down performance in the server. So, I am looking to use the 'tryLock...' in the read lock part of the code and by putting in the 'try' get rid of the deadlocks. The only problem is that if the 'try' fails, the clients will have to retry, but that's already in the client code, so that might not be too bad. If I can get rid of these deadlocks, I'm making a big step forward for stability. We'll see how the tests go.