Search code examples
c++multithreadingboostboost-mutex

Pass class object having mutex to boost::thread by reference


I would like to start multiple instances of a function which performs some calculations. The function takes a class object and as the class includes a shared_mutex I pass it by reference so all threads access the class via the same object.
If I try to start the function via boost::threads (even just one) I do get the compile error:

/usr/include/boost/thread/pthread/shared_mutex.hpp:173:9: error:
‘boost::shared_mutex::shared_mutex(boost::shared_mutex&)’ is private
     BOOST_THREAD_NO_COPYABLE(shared_mutex)
     ^
/cl_shared.h:12:7: error: within this context
class cl_shared {
      ^

If I call the function directly via main it works fine. How to run the function multiple times? The mutex is there for thread saftey as more than one thread reads/writes to the class. Broken down it looks like:

class cl_shared {
public:
    //constructor 
    cl_shared() { }; 

    //functions here using the mtx
    void hello() {
        cout<<"hello"<<endl;
    };

    boost::shared_mutex mtx;
    int aint;
};

cl_shared shared;

int main(int argc, char **argv) {
 // XMA::mov_avg(shared, arg1); //does work

 // boost::thread worker1(XMA::mov_avg, shared, arg1); //error: mutex is private
 // boost::thread worker2(XMA::mov_avg, shared, arg1); //like to start it simultaneously;
 //boost::thread worker1v2(XMA::mov_avg, boost::ref(shared), 0, avg_typ, pos_vel, w_leng, parse); //does compile, but is it ok?
}

Function looks like:

//the function head:
void mov_avg(cl_shared &shared, int arg1){
 //do sth.
}

Solution

  • Since mutex is non-copyable, any object which holds it as a non-static member is also non-copyable. You need to pass the instance of your class as either pointer of reference. To pass it by reference, use boost::ref (or, better, std::ref) and make sure your thread function accepts it's arguments by reference as well.