Recommended practices for re-entrant code in C, C++

廉价感情. 提交于 2019-12-31 22:38:10

问题


I was going through a re-entrancy guide on recommended practices when writing re-entrant code.

What other references and resources cover this topic?

What lint-like tools can be used to check for these issues?


回答1:


The guide is sufficient.

My personal rule of thumbs are only 2 for re-reentering code:

  1. take only pass by value parameters, used only value passed in as parameters in the function.

  2. if I need to use any global parameters or pointer (for performance or storage sake), use a mutex or semaphore to control access to it.




回答2:


  • Do use local variables.
  • Don't use static locals or global variables, even TLS will not help you with recursion / reentrancy.
  • Restore all your invariants before doing callbacks.
  • Don't hold locks while you do callbacks. If you absolutely must (and I would still go looking for a way to avoid it) then make sure you know what happens if you try to re-enter your lock on the thread that already holds it. At a minimum you have to test for this, otherwise depending on the lock you'll get deadlocks or broken invariants (i.e. corruption).



回答3:


None really. Writting non-reentering code is usually more difficult than re-entring. Just follow those simple guidelines and don't try to do anything too waky and you'll be fine.

Non-reentering code is usually written for high-performance issues.




回答4:


  1. A reentrant function may not use variables in a non-atomic way unless they are stored on the stack of the calling task or are the private variables of that task.
  2. A reentrant function may not call other functions which are not reentrant.
  3. A reentrant function may not use the hardware in a non-atomic way.

Ref: Page 462 [AN INTRODUCTION USING THE RENESAS RX62N MICROCONTROLLER] [James M. Conrad]



来源:https://stackoverflow.com/questions/3240241/recommended-practices-for-re-entrant-code-in-c-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!