[Linux] --- thread-safe reentrant VS

What are thread-safe and reentrant

Thread-safe :
the program has a number of shared data concurrently executing threads, the thread-safe code through a series of mechanisms to ensure that each thread can be safely and properly executed, the data does not appear accidental contamination from happening.

Reentrant :
the different execution flow call the same function, a current process has not been performed, there are other execution flow enters again, we call the re-entry. In the case where a function of re-entry, the results will not be any different or any problems, the function is called reentrant function, otherwise, the function is not reentrant

The common thread unsafe situation (emphasis)

  • Function does not protect shared variables
  • With the status function is called, the state changes function
  • Function that returns a pointer pointing to a static variable
  • Thread unsafe function call function

Common thread-safe situation (emphasis)

  • Each thread only read permissions to the global variable or static variable, but there is no written permission, these threads are generally safe
  • Class or interface to a thread is atomic
  • Switching between multiple threads does not result in the execution result of the ambiguity interface

Common reentrant case

  • Call malloc / free functions because malloc function is to manage the global list of the heap
  • Calling the standard I / O library functions, many implementations of the standard I / O library are by the way to use non-reentrant global data structure
  • Reentrant function in vivo use static data structure

Common non-reentrant case

  • Do not use global variables or static variables
  • Do not use open up the space with malloc or new
  • Do not call non-reentrant functions
  • Do not return static or global data, the caller has all the functions of the data provided
  • Using local data, to protect the global data or by making a local copy of global data

Reentrant and thread-safe contact

  • Functions are reentrant, that is thread-safe
  • Functions are not reentrant, it can not be used by multiple threads, the thread may lead to security problems
  • If a function has a global variable, the function is neither safe nor thread-reentrant

Reentrant and thread-safe differences (focus)

  • Reentrant function is a thread-safe function
  • Thread safety is not necessarily re-entrant, and is reentrant functions must be thread-safe.
  • If the visit will add a critical resource lock, then this function is thread-safe, but if this reentrant functions if the lock has not yet released it will produce a deadlock, and therefore is not reentrant
Published 57 original articles · won praise 301 · views 40000 +

Guess you like

Origin blog.csdn.net/L19002S/article/details/105078742