为什么这段代码线程安全?

时间:2016-06-16 12:03:38

标签: linux multithreading mutex

对于此代码,它表示线程不安全:

/* thread-unsafe function */
int increment_counter()
{
        static int counter = 0;

        counter++;
        return counter;
}

但是对于下面的代码,它被认为是线程安全的:

/* 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;
}

我无法理解。谁能解释一下呢?

0 个答案:

没有答案