【问题标题】:Pass class object having mutex to boost::thread by reference通过引用将具有互斥锁的类对象传递给 boost::thread
【发布时间】:2016-02-29 11:54:42
【问题描述】:

我想启动一个函数的多个实例来执行一些计算。该函数采用一个类对象,并且由于该类包含一个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.
}

【问题讨论】:

标签: c++ multithreading boost boost-mutex


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-09-16
    • 2016-12-27
    • 1970-01-01
    • 2013-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    相关资源
    最近更新 更多