2

I am using plain old c.

I have a function that uses static local variables and is therefore non-reentrant. I would like to remove the use of the static locals and make the function reentrant.

Any tips or design recommendations for how to do this?

Is this question too vague? Does it require more details about the design I'm currently working with? Or are there general design patterns that can be followed in this sort of situation?

dtmland
  • 2,136
  • 4
  • 22
  • 45
  • You generally can't do it to an existing function, you need to create a new function with a different interface. Take a look at the difference between `strtok()` and `strtok_r()`, for example. – Barmar Jul 10 '13 at 16:38
  • *Does it require more details about the design I'm currently working with?* yes , it requires more details. – 0decimal0 Jul 10 '13 at 16:42
  • Have a look at this post :http://stackoverflow.com/questions/261311/what-is-the-difference-between-re-entrant-function-and-recursive-function-in-c – 0decimal0 Jul 10 '13 at 16:48

2 Answers2

2

Instead of using static locals to maintain state, have the caller pass those state variables to your function as parameters. It means your caller will have to maintain state, but that's usually what you want anyway.

John Bode
  • 119,563
  • 19
  • 122
  • 198
1

you can protect your code with one of this solutions:

  1. Use Mutex or Semaphore with your static variable.
  2. Disable the Interrupts before the function and Enable it after finishing.
  3. Disable scheduling for Multitasks system.
  4. use Local variables.
Mina Samir
  • 162
  • 12