Hy,
I have started working with threads in C++ (boost threads),
and I have found my self in the following situation:
boost::mutex::scoped_lock lk(monitor);
while (buffered == 0) {
buffer_not_empty.wait(lk);
}
And I was wandering if the int variable buffered should be volatile.
I would say that it should, to prevent a optimization like this, at compile time:
boost::mutex::scoped_lock lk(monitor);
while (true) {
buffer_not_empty.wait(lk);
}
but since this is a example from the boost documentation, I may be missing something…
is a lock/mutex/condition enough to prevent this kind of optimizations ? like in java ?
You need not mess with
volatile.volatilehas absolutely nothing to do with multithreading. Even if the compiler doesn’t optimize things away to the loop you mention somehow, your CPU might make the same optimization, andvolatiledoes not affect the CPU.waitshould contain the necessary memory barrier instructions required make this operate as expected.