Is there a way to automatically lock an STL container on access, without having to lock and release around it?
+4
A:
The currrent C++ standard does not say anything about thread safety for STL containers. Officially it is possible for an STL implementation to be thread safe, but it's very unusual. If your STL implementation is not thread safe, then you will need to "lock and release around it" or find some other way to coordinate access.
You may be interested in Intel's Threading Building Blocks which includes some thread safe containers similar to STL containers.
Max Lybbert
2009-10-30 05:32:37
+1 for mentioning TBB
Éric Malenfant
2009-10-30 13:14:43
+1
A:
After much Googling, it seems the way to do it is to create a wrapper around your container. e.g.:
template<typename T>
class thread_queue
{
private:
std::queue<T> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(T const& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
etc ...
}
Gerald Kaszuba
2009-10-30 05:42:16
You should own the lock when you call boost::condition_variable::notify_one()
Charles Salvia
2009-10-30 06:24:08
Also, you should give your condition variable a proper name like "not_empty" and "not_full" because these are the conditions a thread might want to wait for.
sellibitze
2009-10-30 08:12:11