c++ - 线程中的回调函数

标签 c++ multithreading callback boost-thread

我收到错误 error C2248: 'boost::mutex::mutex' : 无法访问类 'boost::mutex' 中声明的私有(private)成员

我已经看到了有关同一错误的各种问题,但还无法找出解决方案。我正在尝试在线程中实现回调函数。回调函数是通过成员函数调用的,如下所示:

// 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;
}

我正在使用多线程,因为还有其他函数需要与之一起运行。感谢您的帮助。

最佳答案

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

并且您需要在 boost::thread 处进行 boost::bind 检查这个 Using boost thread and a non-static class function

关于c++ - 线程中的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20026769/

相关文章:

c++ - 所有指针都被认为是迭代器吗?

c++ - 深度神经网络的图像识别精度,float 还是 double?

android - Asynctask(从 alarmmanager 执行)回调到 ui

C++ API : Modifing internal objects

c++ - 在 C 中使用带有命名空间的 C++

reactjs - 在 React js 中对 .map 数据进行排序(在顶部显示最新日期)

c++ - CPP : How to create a thread with method that requires pointer?

java - 停止特定的 Java 线程

javascript - Express-node 服务器在 GET 上返回空数组

jquery 无法在 IE 中使用 ajax 响应作为上下文