在互斥锁定后递增共享变量不返回预期输出

Incrementing shared variable not returning expected output after mutex lock

我正在调用 100 个线程,每个线程应该将一个共享变量递增 1000 次。所以预期的输出应该是100000。当然当多个线程试图递增一个共享变量时,你也可以得到不是100000的输出(你不太可能得到100000)。

为了解决这个问题,我在递增变量的方法中加了一个锁,以便一切都同步运行。

但是,我仍然收到 99000、98000 和有时 100000 之类的数字。但它应该始终是 100000,因为我有一把锁,对吗?

这就是我的

volatile unsigned int count = 0;

void *increment(void *vargp);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main() {
    fprintf(stdout, "Before: count = %d\n", count);

    int j;
    // run 10 times to test output
    for (j = 0; j < 10; j++) {
        // reset count every time
        count = 0;

        int i;
        // create 100 theads
        for (i = 0; i < 100; i++) {
            pthread_t thread;

            Pthread_create(&thread, NULL, increment, NULL);
        }

        fprintf(stdout, "After: count = %d\n", count);
    }

    return 0;
}          

void *increment(void *vargp) {
    int c;

    // protected by mutex lock
    pthread_mutex_lock(&mutex);

    // increment count 1000 times
    for (c = 0; c < 1000; c++) {
        count++;
    }

    pthread_mutex_unlock(&mutex);

    return NULL;
}    

您是否正在等待所有线程完成?看起来不像你。试试 How can I wait for any/all pthreads to complete?

以下代码,运行 在 ubuntu linux 14.04 上编译干净并正确执行。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define UNUSED(x)      (void)(x)
#define NUM_TESTS      (10)
#define NUM_INCREMENTS (1000)
#define NUM_THREADS    (100)

volatile unsigned int count = 0;

void *increment(void *vargp);

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main( void )
{
    fprintf(stdout, "Before: count = %d\n", count);

    pthread_t thread[NUM_THREADS];
    int j;

    // run 10 times to test output
    for (j = 0; j < NUM_TESTS; j++)
    {
        // reset count every time
        count = 0;

        int i;
        // create 100 theads
        for (i = 0; i < NUM_THREADS; i++)
        {
            pthread_create(&thread[i], NULL, increment, NULL);
        }

        for( i=0; i < NUM_THREADS; i++ )
        {
            void *retval;
            pthread_join( thread[i], &retval);
        }

        fprintf(stdout, "After: count = %d\n", count);
    }

    return 0;
}

void *increment(void *vargp)
{
    UNUSED(vargp);
    int c;

    // protected by mutex lock
    pthread_mutex_lock(&mutex);

    // increment count 1000 times
    for (c = 0; c < NUM_INCREMENTS; c++)
    {
        count++;
    }

    pthread_mutex_unlock(&mutex);

    pthread_exit( NULL );
}