What kind of code can be called “re-entrant”?

前端 未结 9 1239
时光说笑
时光说笑 2020-12-24 02:34

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

相关标签:
9条回答
  • 2020-12-24 03:01

    Code that can be called by different threads running in parallel. So, the code:

    1. can have local variables (allocated on each thread's stack)
    2. should have guarded global and static variables, since the threads will be sharing them and there will be a race condition here.
    0 讨论(0)
  • 2020-12-24 03:05

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-24 03:07

    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.

    0 讨论(0)
提交回复
热议问题