[Solved] why is race condition in following code [closed]


Assuming this is called from multiple threads, the static variable i needs to be protected.
This can be done with a lock as mentioned before, or in this case using an atomic increment operation which is more efficient.
If you are using the gcc compiler it would look something like this:

static int i=0;
void some_fun()
{
  int local_i = __sync_add_and_fetch(&i, 1);
  if(2==local_i)
  {
    printf("some message");
  }
}

The __sync_add_and_fetch() function adds the second param to the first and returns the sum. All this in as an atomic operation. This is more efficient than grabbing and releasing a lock

solved why is race condition in following code [closed]