0

我想启动一个执行一些计算的函数的多个实例。该函数接受一个类对象,并且由于该类包含一个shared_mutex我通过引用传递它,因此所有线程都通过同一个对象访问该类。
如果我尝试通过 boost::threads (即使只有一个)启动该函数,我确实会收到编译错误:

/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 {
      ^

如果我直接通过 main 调用该函数,它可以正常工作。如何多次运行该功能?互斥锁用于线程安全,因为多个线程读取/写入类。分解它看起来像:

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?
}

函数看起来像:

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

1 回答 1

0

由于互斥锁是不可复制的,任何将它作为非静态成员保存的对象也是不可复制的。您需要将类的实例作为引用指针传递。要通过引用传递它,请使用boost::ref(或更好,std::ref)并确保您的线程函数也通过引用接受它的参数。

于 2016-02-29T14:16:55.583 回答