0

如果我想在函数中运行一段代码,仅从函数的第二次调用开始,

问题:

  1. 这样做有什么不对吗?

  2. 我怎么可能做到这一点?使用静态变量来做到这一点是个好主意吗?

4

3 回答 3

1
  1. 多线程将是一个问题。为了防止这种情况,如果需要,您可能需要类似mutex的东西。

  2. 像这样:

    void someFunction()
    {
       static bool firstRun = true;
       if (!firstRun)
       {
          // code to execute from the second time onwards
       }
       else
       {
          firstRun = false;
       }
       // other code
    }
    
于 2013-09-05T14:06:21.940 回答
1

这个问题有两个答案,取决于您是否必须处理多线程序列化。

无线程:

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
}

使用线程:我将编写通用样板,但此代码是系统特定的(需要原子 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
}
于 2013-09-05T14:44:41.800 回答
-1

添加一个全局计数器。例如:-

静态 int 计数器 = 0;

public void testFunc(){

    if(counter==1){

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

     }
    counter++;

}
于 2013-09-05T13:52:59.570 回答