c++functionstaticinvocation

Execute a piece of code in a function from the second invocation onwards


If I desire to run a piece of code in a function, only from the second invocation of the function onwards,

Questions:

  1. Is there something wrong to do that?

  2. How can I possibly achieve this ? Is using a static variable to do this a good idea ?


Solution

  • There's two answers to this question, depending on whether you have to deal with multi-threaded serialization or not.

    No threading:

    void doSomething() {
        static bool firstTime = true;
        if (firstTime) {
           // do code specific to first pass
           firstTime = false;
        } else {
           // do code specific to 2nd+ pass
        }
        // do any code that is common
    }
    

    With threading: I'll write the generic boilerplate, but this code is system specific (requiring some variant of an atomic compareAndSet).

    void doSomethingThreadSafe() {
        static volatile atomic<int> passState = 0;
    
        do {
            if ( passState == 2 ) {
                //perform pass 2+ code
                break;
            } else
            if ( passState.compareAndSet(0,1) ) { // if passState==0 set passState=1 return true else return false
                //perform pass 1 initialization code
                passState = 2;
                break;
            } else {
                //loser in setup collision, delay (wait for init code to finish) then retry
                sleep(1);
            }
        } while(1);
    
        //perform code common to all passes
    }