C/C++
Article directory
Thread safety and function reentrancy
Reentrant and thread safe, these two are completely different concepts;
Reentrant functions can only occur under signal. For example, a function is interrupted during execution, and it is called again in the interrupt processing function. These two (each) calls can produce correct results, so the reentrant input function;
reentrant function
See a non-reentrant example:
void sig_handler(int sig)
{
...
gethostbyname("www.baidu.com");
....
alarm(1);
}
int main()
{
signal(SIGALRM,sig_handler);
alarm(1);
while(1){
....
gethostbyname("www.google.com");
printf(...);
}
return 0;
}
The internal implementation of gethostbyname has a static local variable, or a static global variable;
This means that the call to gethostbyname in main has just been executed or only half executed. At this time, the signal comes, go to sig_handler and continue to call gethostbyname. Since the implementation is a static variable, the subsequent call to gethostbyname will overwrite the previous data .
Therefore, it is conceivable that if a function uses static/global variables for data processing or returns this static/global variable, it must be a non-reentrant function;
thread safety
Simply put, it is a locking operation;
so thread-safe functions must be reentrant? The answer is no
For example:
malloc is thread-safe, it will operate a global linked list, once it is interrupted by sigal during execution, it will be finished directly
pthread_mutex_lock is thread safe, once the execution process is interrupted, another pthread_mutex_lock may directly deadlock or destroy the internal state during the interrupt processing
For example: , thread safe? Can it be executed correctly after an interruption?
int func(){
static int i = 0;
lock ;
++i;
unlock ;
return i;
}
In short, thread safety and reentrancy are two concepts, although there are some intersections between them;
If a static/global variable is used in a function, it is basically a non-reentrant function, of course, it depends on the implementation; if this function is added
lock, then it is thread-safe, if the static/global variables are also deleted internally, and no additional calls to non-reentrant functions are made, then it is a
Functions that are thread-safe and reentrant.
Finally, is a reentrant function a thread-safe function?
Not necessarily; but in general reentrant functions are thread-safe,
reason:
Think about it yourself, the characteristic of non-reentrant functions is [using or returning static/global variables or using additional non-reentrant functions]
Then the reentrant function must not call or use those things,