This is a mainly theoretical question, so please don't stone me for bringing it up.
Now, I've read that recursive mutexes are evil. And I get why.
However assume you have this little situation:
LockMutex();
for(ListIterator it = List.begin(); it != List.end(); ++it) {
//doStuff, which might possibly alter the List contents
}
UnlockMutex();
Seems familiar to many, I'm sure. Now the big question is, how to handle this situation correctly?
After putting some thought into it and without the use of a recursive mutex (which are evil), the only possible option is to do something like this:
LockMutex();
for(ListIterator it = List.begin(); it != List.end(); ++it) {
UnlockMutex();
//doStuff, which might possibly alter the List contents
LockMutex();
}
UnlockMutex();
Now, one of the reasons why 'recursive mutexes are evil' is, that they require additional overhead to remember who has the lock and how often it was locked...and it's no additional overhead to unlock and relock the mutex on every single iteration?
Furthermore, what is to happen, if another thread accesses the list while the mutex is unlocked and alters the very element this iteration is on? Possibly removes the element we're currently on, essentially invalidating the iterator, leading to a very nasty bug?
I know that by locking the entire list for the duration of the iteration is a terrible bottleneck, but I think for most light applications that's something I'd be able to live with compared to the risk of crashing the entire application by allowing a second thread to mess with the list while I'm not looking.
I've also looked at ReaderWriter-Locks, but the problem remains the same. Technically, as soon as the content of the loop MAY alter the list (which is hard to foresee, especially if you're working with polymorphism), you'd need to acquire a writing lock to the list, which again means, that no other thread may access the list at the time. And the issue of an iterator getting invalidated still stands.
So yeah, any ideas or words of wisdom for me?