0

I was wondering how to share a mutex in one class amongst different instances of another class.

Right now, I have a class, Indexer, that has a Boost mutex and condition_variable as private member variables. I create an auto_ptr of the Indexer class in my main and pass a pointer of Indexer to instances of another class, Robot.

I do that like the following:

std::auto_ptr<Indexer> index_service(new Indexer());
Robot a(*index_service.get());
Robot b(*index_service.get());
Robot c(*index_service.get());

Robot's constructor is:

Robot(Indexer &index_service)
{
  this->index_service = index_service;
}

Robot's header looks like:

class Robot
{
   public:
     Robot(Indexer &index_service);
   private:
     Indexer index_service;
};

However, since mutexes are noncopyable, I get an error.

I was thinking of making the mutex and condition_variable shared_ptrs but I read that this could result in unexpected behaviour.

Can someone please show me the proper/correct way to do this?

Thank you!

noko
  • 1,129
  • 2
  • 14
  • 25

3 Answers3

2

I'm not a C++ guru, but it seems like the unholy mix of pass by reference and pointers is trouble here.

Specifically you do this: this->index_service = index_service;
But the value is passed in as Indexer &index_service
And since the local index_service is type Indexer index_service;
I believe that the assignment implies copy.

I assume you only want one instance of the Indexer, so you are really meaning to store a reference to it in your Robot class. To do that you would want to have your constructer take a pointer (which is what the *index_service.get() call is getting you anyway). Further you want your class variable to be a pointer type.

Jon L
  • 273
  • 1
  • 7
  • This seems to have worked out, thanks! I need to go back over some of my code and make sure I'm not making local copies... After doing this, I needed to change it to index_service.get() – noko Sep 03 '12 at 03:46
  • Ah yes, that would make sense. My statement "which is what the *index_service.get() call is getting you anyway" is wrong... That would de-ref the return of get (giving you the object) which is fine if your constructor is pass by reference because c++ does the magic for you... – Jon L Sep 03 '12 at 03:52
0

Declare a static boost::mutex in your class. Remember to define it in your .cpp file.

Check here: Using static mutex in a class

Community
  • 1
  • 1
Michal M
  • 122
  • 9
0

Just as another option you can use std::shared_ptr in place of std::auto_ptr and in your Robot class change Indexer tostd::shared_ptr`.

class Robot
{
public:
    Robot( std::shared_ptr<Indexer> const &index_service)
    {
        this->index_service = index_service;
}
private:
   std::shared_ptr<Indexer> index_service;
};

std::shared_ptr<Indexer> index_service(new Indexer());
Robot a(*index_service.get());
Robot b(*index_service.get());
Robot c(*index_service.get());
BigBoss
  • 6,904
  • 2
  • 23
  • 38