1

I have some STL containers that i need to share between objects of 2 different types - say A & B. The container is defined in class A and used as reference in class B. Since STL containers are not thread safe, I was planning to define boost::mutex in A and store it as reference in class B.

That plan has obviously failed since I realize that boost::mutex is not copyable. I can't move the container out of class A or provide a wrapper over the container. What would you do here?

And why can't mutexes be copied?

4

2 回答 2

2

我不是 100% 确定我可以遵循,但是如果你想在一个类的两个实例之间共享一个互斥锁以保护共享资源,为什么不直接使用boost::shared_ptr<boost::mutex>从两个实例访问互斥锁呢?

当你需要共享资源时,这应该是一个通用的策略,你也可以考虑使用boost::shared_ptr容器本身,但是没有看到你的代码,很难提供一些具体的建议。

于 2013-09-28T17:52:38.563 回答
0
class Sample
{
  std::vector<int> v;
private:
  struct Mut;
};

struct Sample::Mut
{
  boost::mutex mut_;
};

或者

class Sample {
    std::vector<int> v;
public:
    boost::shared_ptr<boost::mutex> mutt;
    Sample() : mutt(new boost::mutex) {}
};

boost::mutex现在您可以在其他提供对互斥体包装器的访问的对象中引用此示例的 ,或者可以直接使用Mut结构或boost::shared_ptr. boost::shared_ptr是可复制的,它的所有副本都将共享给定的互斥锁。


为什么不能复制互斥锁?

因为 mutex 是不可复制的。这是它源自boost::noncopyable

#include <boost/thread/mutex.hpp>

class mutex:
    boost::noncopyable
{

类 noncopyable 是一个基类。当您想禁止复制构造和复制分配时,从 noncopyable 派生您自己的类。

实际上,您不需要它们的副本,因为它没有用,而是您希望在许多对象中共享相同的实例并引用一个保护对单个资源的访问的互斥锁。

来自<boost/noncopyable.hpp>

//  Private copy constructor and copy assignment ensure classes derived from
//  class noncopyable cannot be copied.

//  Contributed by Dave Abrahams

namespace noncopyable_  // protection from unintended ADL
{
  class noncopyable
  {
   protected:
#ifndef BOOST_NO_DEFAULTED_FUNCTIONS
    BOOST_CONSTEXPR noncopyable() = default;
    ~noncopyable() = default;
#else
    noncopyable() {}
      ~noncopyable() {}
#endif
#ifndef BOOST_NO_DELETED_FUNCTIONS
        noncopyable( const noncopyable& ) = delete;
        noncopyable& operator=( const noncopyable& ) = delete;
#else
    private:  // emphasize the following members are private
      noncopyable( const noncopyable& );
      noncopyable& operator=( const noncopyable& );
#endif
  };
}

typedef noncopyable_::noncopyable noncopyable;
于 2013-09-28T18:00:54.200 回答