ros多线程订阅C++程序
时间: 2024-04-18 07:05:18 浏览: 25
以下是一个使用ROS多线程订阅C的示例程序:
```
#include <ros/ros.h>
#include <std_msgs/Int32.h>
#include <pthread.h>
void* subscriberThread(void* arg)
{
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe<std_msgs::Int32>("topic", 1000, [](const std_msgs::Int32::ConstPtr& msg){
ROS_INFO("Received: %d", msg->data);
});
ros::spin();
return NULL;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "multi_threaded_subscriber");
ros::NodeHandle nh;
pthread_t thread;
pthread_create(&thread, NULL, subscriberThread, NULL);
ros::spin();
pthread_join(thread, NULL);
return 0;
}
```
在这个程序中,我们创建了一个`subscriberThread`函数来作为新的线程。在这个函数中,我们创建了一个ROS订阅者来订阅`topic`话题,并在回调函数中输出接收到的数据。在主函数中,我们创建了一个新的线程来运行`subscriberThread`函数,然后继续在主线程中调用`ros::spin()`来处理其他的ROS回调函数。最后,我们使用`pthread_join`函数等待子线程结束。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)