I'm coding a monitor to mutually exclude access to the methods of a std::list
What I have now is basically this:
list<int> l;
class monitor{
public:
void m_add(int x){
//lock use of m_remove
//lock use of m_add
l.push_back(x);
//unlock use of m_add
//unlock use of m_remove
}
void m_remove(int x){
//lock use of m_remove
//lock use of m_contains
//lock use of m_add
l.remove(x);
//unlock use of m_add
//unlock use of m_contains
//unlock use of m_remove
}
bool m_contains(int x){
//lock use of m_remove
bool found = find(l.begin(), l.end(), x) != l.end();
//unlock use of m_remove
return found;
}
private:
mutex mtx_remove;
mutex mtx_add;
mutex mtx_contains;
};
Inside main function I create a thread to run the add function, e.g. thread t(m.m_add, 1);
and I get the error
error: invalid use of non-static member function
I understand (by looking at other answers around here) that I should run the thread as in thread t(&monitor::m_add, 1);
and declaring all the methods as static, but I need to instantiate an object of monitor
in order to create the mutexes (or locks, or whatever) and make them private on main's scope.
What is the most appropriate solution for this case? It'd be interesting if the locks were only accessible in the scope of the monitor class (by the way, I also intend to put the list<int> l
inside the monitor class in the future.)
Your thread function has to be static. To access member functions from the thread pass a pointer to your object to the thread function when you create it.