Ask Your Question
1

Disabling parallelism of subscribers in Python

asked 2020-07-03 04:31:03 -0500

omercan_s gravatar image

Hi all, I have observed that rospy is enabling the parallelism of subscriber callbacks which means that before one callback that receives a message from a topic finishes, another callback that receives a message from another topic can start execution. This might be ideal for most applications, but in my case it is not the desired behavior. To make it simple and general I am sharing the below code that would serve as an example:

#!/usr/bin/env python

import rospy
from std_msgs.msg import String

def callback1(msg):
    while(True):
        print("Callback1: %s" % (msg.data))
        rospy.sleep(1)

def callback2(msg):
    while(True):
        print("Callback2: %s" % (msg.data))
        rospy.sleep(1)

def main():
    rospy.init_node('foo')
    rospy.Subscriber('foo1', String, callback1, queue_size=1)
    rospy.Subscriber('foo2', String, callback2, queue_size=1)
    rospy.spin()

if __name__ == '__main__':
    main()

And the output is like:

Callback1: qwe
Callback2: asd
Callback1: qwe
Callback2: asd
Callback1: qwe

Is there any way to force a node to use a single thread for all of its callbacks which would mean a callback blocking the others from starting to execute until it finishes? Thanks in advance!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2020-07-27 09:10:12 -0500

Mermy gravatar image

updated 2020-07-27 09:11:08 -0500

Callbacks are, by definition, parallel. I don't think there is a way to make them not parallel. What you can do is to set up a system of semaphores i.e. shared variables that block execution of the other thread until the one that is being processed finishes. Anyway, be careful when blocking callbacks, if you have a blocked callback and another message arrives, it will create another instance of your callback and you will have two blocked callbacks.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

4 followers

Stats

Asked: 2020-07-03 04:31:03 -0500

Seen: 44 times

Last updated: Jul 27 '20