Skip to content

Instantly share code, notes, and snippets.

@sethrh
Created February 7, 2023 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethrh/8782832af5c456eedf84facf7adb2cca to your computer and use it in GitHub Desktop.
Save sethrh/8782832af5c456eedf84facf7adb2cca to your computer and use it in GitHub Desktop.
Program to test for a race condition in rostopic handlers
# Program to test for a race condition in rostopic handlers
# Run (note the single & to put the first pub in the background and simultaneously start the second)
# $ rostopic pub -1 /test_topic1 std_msgs/String "data: 'hello1'" & rostopic pub -1 /test_topic2 std_msgs/String "data: 'hello2'"
# Both topic handlers should fire nearly simultaenously.
# Each topic reads the global variable, then increments it by 1.
# When one thread increments the GLOBAL from 1 to 3, you have a race condition.
import rospy
from std_msgs.msg import String
import threading
GLOBAL = 1
def handler1(msg):
global GLOBAL
rospy.loginfo("In thread %s/%s, GLOBAL is %d", threading.current_thread().ident, threading.current_thread().name, GLOBAL)
GLOBAL += 1
rospy.loginfo("Incremented global in thread %s, now GLOBAL is %d", threading.current_thread().name, GLOBAL)
def handler2(msg):
global GLOBAL
rospy.loginfo("In thread %s/%s, GLOBAL is %d", threading.current_thread().ident, threading.current_thread().name, GLOBAL)
GLOBAL += 1
rospy.loginfo("Incremented global in thread %s, now GLOBAL is %d", threading.current_thread().name, GLOBAL)
def main():
rospy.init_node(b'TestNode')
rospy.Subscriber(b'/test_topic1', String, handler1)
rospy.Subscriber(b'/test_topic2', String, handler2)
print("Waiting for publish on /test_topic1 and /test_topic2")
rospy.spin()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment