For this code it says that it is thread unsafe:
/* thread-unsafe function */
int increment_counter()
{
static int counter = 0;
counter++;
return counter;
}
But for below code, it is said to be thread safe:
/* pseudo-code threadsafe function */
int increment_counter();
{
static int counter = 0;
static lock_type counter_lock = LOCK_INITIALIZER;
pthread_mutex_lock(counter_lock);
counter++;
pthread_mutex_unlock(counter_lock);
return counter;
}
I cannot understand it. Could anyone explain more about it?