2

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?

Tom Xue
  • 3,169
  • 7
  • 40
  • 77
  • 2
    The idea is to have a consistent state for your `counter`. This is why it is "captured" during the change. Imagine that 2 threads see counter=0 and increment it at the same time => counter=1 (instead of 2), because both of them think that `counter=0` before `counter++`. So instead of having return 2, you'll have 1. – ROMANIA_engineer Jun 16 '16 at 12:07
  • Thank you! I understand it now, how to change your comment to be the answer? – Tom Xue Jun 16 '16 at 12:13
  • Adding a mutex assures that no one else is incrementing that counter from some other part in the code. Mutex is like a round-robin assuring that only one user/process at the time uses that part of the code. – Ola Jun 16 '16 at 12:59

0 Answers0