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

Should callbacks be simple?

asked 2022-01-13 19:02:51 -0500

matosinho gravatar image

updated 2022-01-14 05:09:18 -0500

I was wondering what is the best thing to do, write very simple callbacks, or to put almost all code inside callbacks. I don't know if there is a general rule, so if you understand more cleary the consequences of having long callbacks vs long main loops, please clarify this to me.

For example, if I have a controller, in the callback I could simply get the input and save it to process and publish in main loop, or I could calculte the output inside the callback and already publish it. Which one should I use? What are the advantages and disadvantages of each approach?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2022-01-14 16:44:17 -0500

miura gravatar image

I understand that there is a limit to the number of callbacks that can be processed at one time. Therefore, the shorter the callbacks are processed, the better the overall system throughput should tend to be.

I think there is a possibility that completing the process in the callback will result in more readable code. It may also lead to a reduction in global variables.

edit flag offensive delete link more

Comments

1

Thank you! For me actually, I think that using functions in mainloop makes it more readable. Also, you can use internal attributes instead of global variables to get the callback result.

matosinho gravatar image matosinho  ( 2022-01-17 09:17:34 -0500 )edit
1

answered 2022-01-14 15:43:18 -0500

bjv-capra gravatar image

Following best practices(and experience), you should try to avoid doing any type of expensive(computationally) or blocking operation on callbacks, as you could see the moment a callback is being executed is similar to an "interrupt" happening and being processed. This means the system halts the operation (of at least one thread) to execute your callback before returning to its normal operation.

Regarding your controller example, your first approach is what I'd suggest following on, you could also have another system picking up on changes that have happened due to callbacks (not necessarily the main loop).

Hope this helps.

edit flag offensive delete link more

Comments

Thank you for the explanation! In another framework that I've used, this is the best practice (put most code in main loop). Nice to know that here is similar.

matosinho gravatar image matosinho  ( 2022-01-17 09:18:56 -0500 )edit

Question Tools

6 followers

Stats

Asked: 2022-01-13 19:02:51 -0500

Seen: 327 times

Last updated: Jan 14 '22