Reentrant Function in CIn this article, we will discuss the reentrant function in C with its properties and examples. If there is a way to stop a function from running in the middle of it, handle the interrupt service routine, and then restart the earlier running function without impairing it, such function is said to be re-entrant function. Reentrant functions are utilized in several applications, like handling hardware interrupts, recursion, and among others. Properties of Reentrant FunctionThere are several properties of the Reentrant function in C. Some main properties of the Reentrant function are as follows:
Examples of Reentrant FunctionHere, we will discuss several examples of Reentrant function in C with their explanation: Example: 1strtok(): A string can be tokenized (divided) into smaller strings depending on a delimiter using the strtok() method. It is not thread-safe because it uses a static pointer to preserve its internal state. The reentrant version strtok_r() can be used to make it reentrant, or the state can be managed externally (for instance, by utilizing different data structures for each thread) or both. Code: Output: Token: Hello Token: world Token: this Token: is Token: a Token: test Example: 2qsort(): The QuickSort algorithm is used to sort an array using the qsort() function. The order of the components can only be determined via a comparison function. The qsort() is not reentrant by default due to its shared workspace, but it may be made reentrant by providing a custom comparison function and a context that contains additional data required for sorting. Code: Output: 1 2 5 6 8 Example: 3rand(): The rand() function creates an integer that is pseudo random. It can be made reentrant by using the reentrant version of rand_r(), which accepts a pointer to an unsigned int as a seed, despite the fact that it is not thread-safe by default (due to shared internal data). Code: Output: Random Number: 212005489 Random Number: 2042157013 Random Number: 2068794670 Random Number: 1367026107 Random Number: 927415125 Note that:- These numbers will vary every time you run the code.Conclusion:In conclusion, reentrant functions in C are crucial to the efficient and secure execution of multi-threaded programs. These functions enable simultaneous calls from several threads to the same function without unintentional interference or data corruption. Reentrant functions provide efficient parallelism while reducing synchronization complexity by keeping independent local data and eliminating the use of shared resources. Next TopicReturn Statement in C |