ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

The accepted answer is not correct, at least with Kinetic. Consider the following:

#!/usr/bin/env python

import threading

import rospy
from std_msgs.msg import Empty

global i
i = 0


def callback(_):
    global i
    i += 1
    j = i
    while not rospy.is_shutdown():
        print('sleeping: %d, thread: %s' % (j, threading.current_thread()))
        rospy.Rate(1).sleep()
    print('exiting loop for %d: %s' % (j, rospy.is_shutdown()))


def main():
    rospy.init_node('foooo')
    sub = rospy.Subscriber('foo', Empty, callback, queue_size=1)


if __name__ == '__main__':
    main()
    rospy.spin()

Then, call rostopic twice by running the following command twice in parallel in different shell sessions:

rostopic pub /foo std_msgs/Empty "{}"

Observe the following output:

sleeping: 1, thread: <Thread(/foo, started daemon 140177158719232)>
sleeping: 2, thread: <Thread(/foo, started daemon 140177150326528)>
sleeping: 1, thread: <Thread(/foo, started daemon 140177158719232)>
sleeping: 2, thread: <Thread(/foo, started daemon 140177150326528)>
sleeping: 1, thread: <Thread(/foo, started daemon 140177158719232)>
sleeping: 2, thread: <Thread(/foo, started daemon 140177150326528)>
sleeping: 1, thread: <Thread(/foo, started daemon 140177158719232)>
sleeping: 2, thread: <Thread(/foo, started daemon 140177150326528)>
sleeping: 1, thread: <Thread(/foo, started daemon 140177158719232)>
sleeping: 2, thread: <Thread(/foo, started daemon 140177150326528)>
sleeping: 1, thread: <Thread(/foo, started daemon 140177158719232)>
sleeping: 2, thread: <Thread(/foo, started daemon 140177150326528)>