Could someone tell me what code can be called \"re-entrant\" code?
I came across this word when reading some real time operating system. What disciplines must be st
Code that can be called by different threads running in parallel. So, the code:
Non-reentrant example
class Test {
int count;
// Here method1() is not reentrant
int method1()
{
return count + 1;
}
}
Reentrant example
class Test {
int count;
// Here method1() is reentrant
int method1(int count)
{
return count + 1;
}
}
Virtually any kind of recursive code could be classified as reentrant (i.e. you can call back into the same method without having finished it), but this is used in particular when talking about locks, mutex, semaphores etc. For example, a lock is re-entrant if once you have the lock you can successfully "lock" the code again (i.e. you don't deadlock yourself) - for example:
public void AddIfNecessary(string s) {
lock(syncObj) {
if(!Contains(s)) Add(s);
}
}
public void Add(string s) {
lock(syncObj) {
list.Add(s);
}
}
public bool Contains(string s) {
lock(syncObj) {
return list.Contains(s);
}
}
Here the fact that the lock is re-entrant means we can call Contains
and Add
without worrying that we already have the "exclusive" lock, making the code simpler. Internally, a counter is used rather than a simple "in use" flag.