Can I know this please?

Prof, I’m trying quiz but I want to know this…
How’s the sequence of execution? Does it execute step by step from top to bottom? or are there any jumps in between from one part of code to the other.
Below is the code. Will it all execute line by line, or are there some jumps? If there are a few breaks, please tell me where?

#! /usr/bin/env python

import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan


def callback(msg):
    decide_direction(msg.ranges)


rospy.init_node('topics_quiz_node', anonymous = True)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, callback)

rate = rospy.Rate(2)
move = Twist()


def decide_direction(ranges):

    straight = ranges[360]
    left = ranges[719]
    right = ranges[0]


    def turn_left():
        if (straight < 1) or (right < 1):
            move.linear.x = 0
            move.angular.z = 0.2
            pub.publish(move)

    def turn_right():
        if left < 1:
            move.linear.x = 0
            move.angular.z = -0.2
            pub.publish(move)
            
    def straight_motion():
        if straight > 1:
            move.linear.x = 0.6
            move.angular.z = 0
            pub.publish(move)

rospy.spin()

Hi @abdulbasitisdost,

It will execute from top to bottom, but it will skip the functions until they are called:

  1. The imports at the top will be done.
  2. def callback is skipped.
  3. Next the following lines are executed:
rospy.init_node('topics_quiz_node', anonymous = True)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, callback)

rate = rospy.Rate(2)
move = Twist()

3b. Once the subscriber is created in the code above, it starts to execute in another thread, calls callback and callback calls decide_direction, etc.
4. The following functions are skipped.
5. The last line is executed.

PS: 1, 2, 3, 4, 5 are executed by the main thread while another thread executes 3b.

Cheers!

1 Like

Thank you Professor. But, why is callback called in another thread instead of the main thread ? And what does it mean to say another thread ?

why is callback called in another thread instead of the main thread?
Subscribers are designed to run in their own, separate threads, and the callback is called by the subscriber and therefore runs in its thread.

And what does it mean to say another thread?
Threads are a way to run different parts of a program simultaneously (vs sequentially). You can read about the basics of threads here:

1 Like