Pergunta

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 ?

Foi útil?

Solução

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
}

Outras dicas

  1. Multi-threading will be a problem. To prevent this, if required, you'll probably need something like a mutex.

  2. Like this:

    void someFunction()
    {
       static bool firstRun = true;
       if (!firstRun)
       {
          // code to execute from the second time onwards
       }
       else
       {
          firstRun = false;
       }
       // other code
    }
    

Add a global counter. eg:-

static int counter = 0;

public void testFunc(){

    if(counter==1){

       ........
       <Execute the functionality>
       ........

     }
    counter++;

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top