Performance: Creating a subscriber node
This affects how quickly messages are received and processed, impacting interaction responsiveness and CPU usage.
import rospy from std_msgs.msg import String from threading import Thread def process_data(data): rospy.loginfo(f"Received: {data.data}") def callback(data): Thread(target=process_data, args=(data,)).start() rospy.init_node('async_subscriber') rospy.Subscriber('chatter', String, callback) rospy.spin()
import rospy from std_msgs.msg import String def callback(data): rospy.sleep(1) # Simulate slow processing rospy.loginfo(f"Received: {data.data}") rospy.init_node('slow_subscriber') rospy.Subscriber('chatter', String, callback) rospy.spin()
| Pattern | Message Handling | Callback Blocking | CPU Usage | Verdict |
|---|---|---|---|---|
| Blocking callback with sleep | Delays next message | Blocks for 1s | High CPU wait | [X] Bad |
| Asynchronous callback with threads | Handles messages promptly | Non-blocking | Efficient CPU use | [OK] Good |
What is the main purpose of a subscriber node in ROS?
Which of the following is the correct way to create a subscriber in ROS 2 Python?
node.create_subscription(____, 'chatter', callback, 10)Given this ROS 2 Python subscriber code snippet, what will be printed when a message with data 'Hello' arrives?
def callback(msg):
print(f'Received: {msg.data}')
node.create_subscription(std_msgs.msg.String, 'chatter', callback, 10)What is wrong with this ROS 2 Python subscriber code?
def callback(msg):
print(msg.data)
node.create_subscription(std_msgs.msg.String, 'chatter', callback())You want to create a subscriber node that listens to the topic 'sensor_data' and prints only messages where the data is greater than 10. Which callback function correctly implements this?
def callback(msg):
# Fill in the condition
if ____:
print(f"Data: {msg.data}")Pass the test and this pattern moves unknown