First, Introduction
Today to see NetEase Open class, Monensin Teacher's software Engineering (c coding practice), talk about reentrant and thread safety, combined with his explanation and my understanding, write this blog post, record.
Second, the relationship between reentrant and thread safety
- Reentrant may not necessarily be thread-safe
- Thread-safe must be reentrant
- Non-reentrant functions must not be thread-safe
Meng Teacher's final summary is very good: thread safety is to expand the scope of reentrant, you can re-enter the function refers to a single function, and thread safety is the real code block reentrant.
Third, my understanding
Reentrant is for a function, the reentrant function is that each variable with which it operates is its own exclusive (or only local variables are manipulated, or the lock mechanism is used to implement mutually exclusive access to shared variables),
Thread safety, however, means that a piece of code (which may contain multiple functions) accesses a variable in its own exclusive (either by using only local variables or by locking mechanisms to implement mutually exclusive access to shared variables).
Reentrant functions are not necessarily thread-safe, so what is the case that reentrant functions are not thread-safe? The following example shows the situation:
pthread_mutex_t g_plus;pthread_mutex_t G_minus; int 0 ; void Plus () { pthread_mutex_lock (&g_plus); G_ncount+ +; Pthread_mutex_unlock (&g_plus);} void minus () { pthread_mutex_lock (&g_minus); G_ncount+ +; Pthread_mutex_unlock (&G_minus);}
In the above code, plus and minus are reentrant functions, but this code is not thread-safe. If you want to make it thread-safe, use a lock for the global variable G_ncount operation.
Thread-Safe Code:
pthread_mutex_t G_mutexcount; int 0 ; void Plus () { pthread_mutex_lock (&g_mutexcount); G_ncount+ +; Pthread_mutex_unlock (&g_mutexcount);} void minus () { pthread_mutex_lock (&g_mutexcount); G_ncount+ +; Pthread_mutex_unlock (&g_mutexcount);}
This block of code is thread-safe because the same lock is used for access to the global variable G_ncount.
Reentrant and thread safe