线程中的回调函数

Callback function in thread

本文关键字:函数 回调 线程      更新时间:2023-10-16

我收到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;
}

我使用的是多线程,因为我需要同时运行其他函数。感谢您的帮助。

运行是一个非静态函数,您不需要按照现在的方式执行只需调用其中的"cloudcp"函数若运行是静态的,我会理解一些代码,但它不是,而且它正在使用这个指针!你可以坚持使用代码,只需保持运行功能的简单

并且您将需要在boost::线程处进行boost:检查这个使用boost线程和非静态类函数

经过一番磨难,终于找到了答案。这种错误的问题是无法复制类(Ref:boost mutex与私有成员发生奇怪错误)。因此,解决方案是:

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

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