简体   繁体   中英

Thread safe C++ std::set that supports add, remove and iterators from multple threads

我正在寻找类似于Java中的CopyOnWriteSet的东西,这个集合支持从多个线程addremove和某种类型的iterators

there isn't one that I know of, the closest is in thread building blocks which has concurrent_unordered_map

The STL containers allow concurrent read access from multiple threads as long as you don't aren't doing concurrent modification. Often it isn't necessary to iterate while adding / removing.

The guidance about providing a simple wrapper class is sane, I would start with something like the code snippet below protecting the methods that you really need concurrent access to and then providing 'unsafe' access to the base std::set so folks can opt into the other methods that aren't safe. If necessary you can protect access as well to acquiring iterators and putting them back, but this is tricky (still less so than writing your own lock free set or your own fully synchronized set).

I work on the parallel pattern library so I'm using critical_section from VS2010 beta boost::mutex works great too and the RAII pattern of using a lock_guard is almost necessary regardless of how you choose to do this:

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);
    }
};

Why not just use a shared mutex to protect concurrent access? Be 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 mutex is a mutex object that is shared by all threads. Mutex is just a wrapper class that hides whatever specific OS primitive you are using.

I've always thought that concurrency and set behavior are orthogonal concepts, so it's better to have them in separate classes. In my experiences, classes that try to be thread safe themselves aren't very flexible or all that useful.

您还可以查看ACE库,其中包含您可能需要的所有线程安全容器。

您不希望内部锁定,因为您的不变量通常需要对数据结构执行多个操作,而内部锁定仅防止步骤同时发生,而您需要保持不同宏操作中的步骤不进行交错。

我能想到的就是使用OpenMP进行并行化,从std中派生一个set类,并在每个批判集操作周围放置一个shell,该操作使用#pragma omp critical声明该操作是关键的。

Qt的QSet类使用隐式共享(写入语义上的复制)和类似的方法与std :: set,你可以看看它的实现,Qt是lgpl。

Thread safety and copy on write semantics are not the same thing. That being said...

If you're really after copy-on-write semantics the Adobe Source Libraries has a copy_on_write template that adds these semantics to whatever you instantiate it with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM