I have some code in a function that goes something like this:
void foo() {
{ // scope the locker
MutexLocker locker(&mutex);
// do some stuff..
}
bar();
}
The function call bar() also locks the mutex.
I am having an issue whereby the program crashes (for someone else, who has not as yet provided a stack trace or more details) unless the mutex lock inside bar is disabled.
Is it possible that some optimization is messing around with the way I have scoped the locker instance, and if so, would making the mutex volatile fix it? Is that a bad idea?
Thanks.
I don’t think someone can actually answer the question, as we (and so do you) haven’t seen the stack back-trace.
Yes, it is, but it’s very, very unlikely. Maybe in more than 99% of the cases, the problem is in the code, not in the optimizations.
However, it is possible that the compiler optimizations "unlock" some other bugs, most likely – undefined behavior, that works fine without optimizations and with them – the UB becomes a crash *
I don’t think it will fix anything and I don’t think you need
volatilefor this.I use wrapper around POSIX threads with
class Mutexandclass MutexLock, the logic is the same as in your case, and there’s novolatilein these classes (except someboolflags and the thread id, but this seems to be irrelevant to the case)"*" I recently had such case – when we compiled an application with
-O2, strange crashes appeared. We investigated this for months, we couldn’t find anything suspicious. Then removed the optimizations and everything started working fine again.Several months later, I found the issue and it appeared to be multithreading one – returning const ref on a place, that we shouldn’t have done this.