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

Revision history [back]

click to hide/show revision 1
initial version

It actually seems like a subscriber process has one thread per topic subscribed per publisher. So if node A subscribes to topic /foo and node B publishes to topic /foo and node C also publishes to topic /foo, node A will have 2 callback threads.

ros_thread_sub.py

#!/usr/bin/env python

import threading

import rospy
from std_msgs.msg import String

def callback(msg):
    print("Msg from %s on thread %s" % (msg.data, threading.current_thread()))

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

if __name__ == '__main__':
    main()

ros_thread_pub.py (starting publisher B and C in separate terminals)

#!/usr/bin/env python

import threading
import sys

import rospy
from std_msgs.msg import String

global proc_id
proc_id = ""

def publisher():
    msg = String(proc_id)
    r = rospy.Rate(1)
    pub = rospy.Publisher('foo', String, queue_size=1)
    while not rospy.is_shutdown():
        print("publishing")
        pub.publish(msg)
        r.sleep()

def main():
    global proc_id
    proc_id = sys.argv[1]
    rospy.init_node(proc_id)
    thread = threading.Thread(target=publisher)
    thread.start()
    rospy.spin()

if __name__ == '__main__':
    main()

Console output:

Msg from B on thread <Thread(/foo, started daemon 140237958694656)>
Msg from B on thread <Thread(/foo, started daemon 140237958694656)>
Msg from B on thread <Thread(/foo, started daemon 140237958694656)>
Msg from B on thread <Thread(/foo, started daemon 140237958694656)>
Msg from C on thread <Thread(/foo, started daemon 140237950301952)>
Msg from B on thread <Thread(/foo, started daemon 140237958694656)>
Msg from C on thread <Thread(/foo, started daemon 140237950301952)>
Msg from B on thread <Thread(/foo, started daemon 140237958694656)>
Msg from C on thread <Thread(/foo, started daemon 140237950301952)>
Msg from B on thread <Thread(/foo, started daemon 140237958694656)>