赞
踩
import rclpy from rclpy.node import Node from std_msgs.msg import String class MinimalPublisher(Node): def __init__(self): super().__init__('minimal_publisher') self.publisher_ = self.create_publisher(String, 'topic', 10) self.timer = self.create_timer(0.5, self.timer_callback) def timer_callback(self): msg = String() msg.data = 'Hello World' self.publisher_.publish(msg) def main(args=None): rclpy.init(args=args) minimal_publisher = MinimalPublisher() rclpy.spin(minimal_publisher) minimal_publisher.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
rclpy.spin(minimal_publisher)
executor=SingleThreadedExecutor()
executor.add_node(minimal_publisher)
executor.spin() # 和上述代码相同
多线程执行器创建可配置数量的线程,以允许并行处理多个消息或事件。
提供了三种 Executor 类型,派生自共享父类:
SingleThreadedExecutor:就是默认使用的单线程执行器,同一时间下只能执行一个线程的任务,其他任务需要排队(阻塞式)
StaticSingleThreadedExecutor:在订阅、定时器、服务服务器、动作服务器等方面优化了扫描节点结构的运行时成本。它只在添加节点时执行一次扫描,而其他两个执行器定期执行扫描此类更改。因此,StaticSingleThreadedExecutor只能与在初始化期间创建所有订阅、计时器等的节点一起使用。
MultiThreadedExecutor:多线程执行器,本文要介绍的重点,但是直接使用它无法起到作用,这里还要引入回调组(Callback groups)的概念
my_callback_group = MutuallyExclusiveCallbackGroup()
my_subscription = self.create_subscription(Int32, "/topic", self.callback, qos_profile=1,callback_group=my_callback_group)
self.group1=MutuallyExclusiveCallbackGroup()
self.group2=MutuallyExclusiveCallbackGroup()
sub1= self.create_subscription(Int32, "/topic1", self.callback, qos_profile=1,callback_group=self.group1)
sub2 = self.create_subscription(Int32, "/topic2", self.callback, qos_profile=1,callback_group=self.group2)
executor=MultiThreadedExecutor(num_threads=3)
self.group1=ReentrantCallbackGroups()
sub1= self.create_subscription(Int32, "/topic1", self.callback, qos_profile=1,callback_group=self.group1)
sub2 = self.create_subscription(Int32, "/topic2", self.callback, qos_profile=1,callback_group=self.group1)
executor=MultiThreadedExecutor(num_threads=3)
import rclpy from rclpy.node import Node from rclpy.callback_groups import ReentrantCallbackGroup from rclpy.executors import MultiThreadedExecutor class Test(Node): def __init__(self): super().__init__('test') self.group=ReentrantCallbackGroup() self.timer1=self.create_timer(0.1,self.timer1CB,callback_group=self.group) self.timer2=self.create_timer(1,self.timer2CB,callback_group=self.group) self.i=0 self.executor=MultiThreadedExecutor(num_threads=3) def timer2CB(self): self.i+=1 def timer1CB(self): print(self.i) def main(args=None): rclpy.init(args=args) test=Test() rclpy.spin(test) test.destory_node() rclpy.shutdown() if __name__=='__main__': main() ```
*下期讲讲ROS2C++的多线程使用
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。