Reference:
1. Excerpt from multithreading and multi-process (summary) http://blog.csdn.net/hairetz/article/details/4281931
To ensure functional thread safety, it is important to consider shared variables between threads.
different threads that belong to the same process share the global extents and heaps in the process memory space. The private thread space consists mainly of stacks and registers.
therefore, for different threads of the same process, each thread's local variables are private, while global variables, local static variables, and variables allocated to the heap are shared. when accessing these shared variables, if you want to ensure thread safety, you must pass the lock method.
To ensure that the function can be re-entered, you need to meet a few conditions:
1. Do not use static or global data inside the function
2. Do not return static or global data, all data is provided by the caller of the function.
3. Use local data, or protect global data by making local copies of global data.
4, do not call the non-reentrant function.
Reentrant is not the same as thread safety, in general, a reentrant function must be thread-safe, but it may not necessarily be true. thread-safe functions include reentrant functions, but not all reentrant functions;
For example: The Strtok function is neither reentrant nor thread-safe; the lock-in strtok is not reentrant, but thread-safe, and Strtok_r is both reentrant and thread-safe.
If our thread function is not thread-safe, then in the case of multi-threaded invocation, the possible consequences are obvious--the value of the shared variable may have unpredictable changes due to the access of different threads, resulting in program errors or even crashes.
Reentrant functions and non-reentrant functions
How do I rewrite a non-reentrant function as a " reentrant function "? < based on the above analysis, this means that the thread-safe function is included .>
A: The only way to turn a non-reentrant function into reentrant is to rewrite it with reentrant rules. In fact it is very simple, as long as you follow a few very easy to understand the rules, then the written function is reentrant.
1) Do not use global variables. Because other code is likely to overwrite these variable values.
2) When interacting with hardware, remember to perform operations like Disinterrupt (), which is to turn off hardware interrupts. Complete the interaction remember to open the interrupt, on some series, this is called "Enter/Exit Core".
3) You cannot call any other function that is not reentrant.
4) Use the stack sparingly. It is best to os_enter_kernal first before use.
The stack operation involves memory allocation, and a little inattention can cause data to be overwritten by other tasks, so use the stack with caution!
Linux: Reentrant and non-reentrant functions