线程中的回调函数

时间:2013-11-17 03:15:33

标签: c++ multithreading callback boost-thread

我收到错误error C2248: 'boost::mutex::mutex' : cannot access private member declared in class 'boost::mutex'

我已经看到了关于同一错误的各种问题变化,但还不能弄清楚解决方案。我试图在一个线程中实现一个回调函数。回调函数通过成员函数调用,如下所示:

// KinectGrabber.h
class KinectGrabber{
private:
      mutable boost::mutex cloud_mutex_;
public:
      KinectGrabber() { };
      void run ();
      void cloud_cb_ (const CloudPtr& cloud);
};
// KinectGrabber.cpp
void KinectGrabber::cloud_cb_ (const CloudPtr& cloud)
{
    boost::mutex::scoped_lock lock (KinectGrabber::cloud_mutex_);
    // capturing the point cloud
}
void KinectGrabber::run() {
      // make callback function from member function
      boost::function<void (const CloudPtr&)> f =
      boost::bind (&KinectGrabber::cloud_cb_, this, _1);
      // connect callback function for desired signal. In this case its a point cloud with color values
      boost::signals2::connection c = interface->registerCallback (f);
}
int main (int argc, char** argv)
{
      KinectGrabber kinect_grabber;
      //kinect_grabber.run(); //this works
      boost::thread t1(&KinectGrabber::run,kinect_grabber); // doesnt work
      t1.interrupt;
      t1.join;
}

我正在使用多线程,因为我需要运行其他功能。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

run是一个非静态函数,你不需要按照你的方式去做 只需在其中调用“cloud_cp”函数即可 如果运行是静态的,我会理解一些代码,但它不是,它正在使用这个指针! 你可以坚持使用代码,只需保持运行功能简单

你需要在boost :: thread上加载:: bind 检查一下 Using boost thread and a non-static class function

答案 1 :(得分:1)

经过一番考验后找到了答案。这种错误的问题是无法复制类(参考:boost mutex strange error with private member)。所以解决方案就是:

boost::thread t1(&KinectGrabber::run,boost::ref(kinect_grabber));

默认情况下,boost :: thread按值复制对象,从而违反了不可复制的标准。将其更改为在线程中通过引用传递可以解决错误。希望它能帮助所有其他人。