Thread safe C ++ std :: set which supports adding, removing and iterators from multithreaded threads
there is none that I know of, the closest is in the threading blocks which has concurrent_unordered_map
STL containers allow concurrent read access from multiple threads as long as you are not doing parallel modification. Often no iteration is needed when adding / removing.
A guide to providing a simple wrapper class is sensible, I would start with something like the code snippet below, protecting the methods that you really need concurrent access, and then providing "unsafe" access to the std :: set base so that people can choose other methods that are unsafe. You can protect access, as well as the acquisition and return of iterators if needed, but this is difficult (even less than writing your own lock set or your own fully synchronized set).
I'm working on a parallel templating library, so I'm using critical_section from VS2010 beta boost :: mutex works great and RAII template using lock_guard is practically necessary no matter how you do it:
template <class T>
class synchronized_set
{
//boost::mutex is good here too
critical_section cs;
public:
typedef set<T> std_set_type;
set<T> unsafe_set;
bool try_insert(...)
{
//boost has a lock_guard
lock_guard<critical_section> guard(cs);
}
};
source to share
Why not use a shared mutex to protect concurrent access? Make sure to use RAII to lock and unlock the mutex:
{
Mutex::Lock lock(mutex);
// std::set manipulation goes here
}
where Mutex :: Lock is a class that locks the mutex in the constructor and unlocks it in the destructor, and the mutex is a mutex object that is used by all threads. Mutex is just a wrapper class that hides whatever OS primitive you are using.
I've always thought that concurrency and given behavior are orthogonal concepts, so it's better to have them in separate classes. In my experience, classes that try to be thread safe on their own are not very flexible or useful.
source to share
Thread safety and copying by write semantics are not the same thing. It said ...
If you really use copy-on-write semantics, there is Adobe Source Libraries copy_on_write
that adds those semantics to whatever you create it with.
source to share