Function thread security and Reentrant
Liu aigui/aiguille. Liu
Thread-safe: If a function can be safely called by multiple threads at the same time, it is called thread-safe. The thread-safe function solves the issue of conflicting access to shared resources when multiple threads call functions.
Reentrant: A function can be used concurrently by more than one thread without worrying about data errors. The reentrant function can be interrupted at any time and run later without data loss. The reusability solves the certainty and repeatability of function running results. The code for reentrant functions is as follows:
1. Do not use static or global data inside the Function
2. No static or global data is returned. All data is provided by the function caller.
3. Use local data or make local copies of global data to protect global data.
4. If you must access global variables, use the mutex mechanism to protect global variables.
5. Do not call the reentrant function.
Relationship between the two:
1. If a function is reentrant to multiple threads, this function is thread-safe.
2. A function is thread-safe, but not necessarily reentrant.
3. reconnection is better than thread security.
For example, strtok functions are neither reentrant nor thread-safe. The strtok of the lock is not reentrant, but thread security. Strtok_r is both reentrant and thread-safe. (For details, refer to the man manual)