Subtle C++ mistake, can you spot it?
- by aaa
I ran into a subtle C++ gotcha, took me while to resolve it.
Can you spot it?
class synchronized_container {
boost::mutex mutex_;
std::vector <T> container_;
void push_back(const T &value) {
boost::scoped_lock(mutex_); // raii mutex lock
container_.push_back(value);
}
...
};
scoped lock is a raii mutex lock, obtains lock on constructor, release lock in destructor.
The program will work as expected in serial, but will may occasionally produce weird stuff with more than one thread.