How do you share a mutex among different instances of a class?
-
29-06-2021 - |
Вопрос
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!
Решение
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.
Другие советы
Declare a static boost::mutex in your class. Remember to define it in your .cpp file.
Check here: Using static mutex in a class
Just as another option you can use std::shared_ptr
in place of std::auto_ptr
and in your Robot
class change Indexer to
std::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());