Threadsafe C ++的Vector类 [英] Threadsafe Vector class for C++

查看:381
本文介绍了Threadsafe C ++的Vector类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道一个快速和肮脏的线程安全向量类的c ++?我是多线程的一些代码,我相信我有的问题是与矢量的使用方式。我打算重写代码,但在我疯狂地重做代码之前,我想用一个线程安全的向量来测试它。我也认为如果这样的事情是在那里,这将是比写我自己的版本容易得多。

解决方案

这是很难的算法。



向量,使其所有成员函数使用互斥体序列化,如Java同步方法。然后对该向量的 std :: remove 的并发调用仍然不安全,因为它们依赖于查看向量并根据他们看到的内容更改它。 p>

因此,您的LockingVector需要专门处理标准算法中的每个模板,以锁定整个事物。但是其他算法如 std :: remove_if 会调用锁定下的用户定义代码。在场景之后静静地执行这种操作是一旦某人开始创建对象的向量时就锁定反转的方法,它们自己内部对所有方法都锁定。



在回答你的实际问题:对不起,不,我不知道一个。为了快速测试所需的类型,我建议您先从:

  template< typename T> 
class LockedVector {
private:
SomeKindOfLock lock;
std :: vector< T> vec;
};

然后将其作为替换容器放入,并开始实现成员函数(和成员typedef和运算符)直到编译。你会很快注意到,如果你的代码使用迭代器的向量上的方式,根本不能使线程安全从内而外,如果需要你可以暂时更改调用代码在这些情况下锁定向量通过公共方法。


Does anyone know a quick and dirty threadsafe vector class for c++? I am multithreading some code, and I believe the problem I have is related to the way the vectors are used. I plan to rewrite the code, but before I go crazy redoing the code, I would like to test it with a threadsafe vector to be sure. I also figure if such a thing is out there, it would be much easier than writing my own version.

解决方案

This is difficult because of algorithms.

Suppose you wrapped vector so that all its member functions are serialised using a mutex, like Java synchronized methods. Then concurrent calls to std::remove on that vector still wouldn't be safe, because they rely on looking at the vector and changing it based on what they see.

So your LockingVector would need to specialize every template in the standard algorithms, to lock around the whole thing. But then other algorithms like std::remove_if would be calling user-defined code under the lock. Doing this silently behind the scenes is a recipe for locking inversion as soon as someone starts creating vectors of objects which themselves internally take locks around all their methods.

In answer to your actual question: sorry, no, I don't know of one. For a quick test of the kind you need, I recommend that you start out with:

template <typename T>
class LockedVector {
    private:
    SomeKindOfLock lock;
    std::vector<T> vec;
};

Then drop it in as a replacement container, and start implementing member functions (and member typedefs, and operators) until it compiles. You'll notice pretty quickly if any of your code is using iterators on the vector in a way which simply cannot be made thread-safe from the inside out, and if need be you can temporarily change the calling code in those cases to lock the vector via public methods.

这篇关于Threadsafe C ++的Vector类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆