I have a function that will generate a unique random number(basically increment previous) to different threads invoking it.
Is this thread safe or is this reentrant.Assume I used static variable for this number.
I have seen in this forum static variables cant be used for reentrant/thread safe.
Does it applies for local/global static.
Or is it implementation defined.
In C, local static
variables are initialized in a thread-safe manner because they're always initialized at program startup, before any threads can be created. It is not allowed to initialize local static
variables with non-constant values for precisely that reason.
void some_function(int arg)
{
// This initialization is thread-safe and reentrant, since it happens at
// program startup
static int my_static = 42;
// ERROR: Initializer is not constant
static int another_static = arg;
...
}
Of course, whether or not the entire function is thread-safe or reentrant depends entirely on how you use the static variables. Since they're effectively identical to global variables, you need to make sure to use proper mutexes when reading or writing them (or other synchronization structures) to ensure thread safety.
In order to ensure that the function is reentrant, you need to carefully examine when and how the function can call itself (perhaps indirectly via another function) and make sure that all global state behaves consistently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With