pthread互斥锁不起作用,每次都获得一个随机值

我正在学习POSIX pthreads,并且在使用互斥锁时,我开始得到一个奇怪的输出。 每次运行代码时,它都会输出一个随机数,而我希望它会输出0。我检查了代码,但无法弄清发生这种情况的原因,因此,如果有人可以向我解释到底出了什么问题,将不胜感激。

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

int num = 0;
pthread_mutex_t mutex;

void* add(void* args)
{
    int sign = *(int*) args;
    for(int i = 0; i < 100; i++)
    {
        pthread_mutex_lock(&mutex);
        num += sign;
        pthread_mutex_unlock(&mutex);
    }
    pthread_exit(NULL);
    return NULL;
}


int main()
{
    pthread_t pool[1000];
    int plus = +1;
    int minus = -1;
    pthread_mutex_init(&mutex,NULL);


    for(int i = 0; i < 500; i++)
        pthread_create(&pool[i],NULL,add,&plus);

    for(int i = 500; i < 1000; i++)
        pthread_create(&pool[i],&minus);

    for(int i = 0; i < 1000; i++)
        pthread_join(pool[i],NULL);

    printf("%d",num);
    return 0;
}
pklimi 回答:pthread互斥锁不起作用,每次都获得一个随机值

以下建议的代码:

  1. 干净地编译
  2. 正确检查错误
  3. 正确初始化互斥锁
  4. 执行所需的功能
  5. 结果为0

注意:函数:pthread_mutex_init()是有效函数,但是NULL的初始值无效

现在,建议的代码:

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

int num = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* add(void* args)
{
    int sign = *(int*) args;

    for(int i = 0; i < 100; i++)
    {
        pthread_mutex_lock(&mutex);
        num += sign;
        pthread_mutex_unlock(&mutex);
    }

    pthread_exit(NULL);
}


int main( void )
{
    pthread_t pool[1000];
    int plus = +1;
    int minus = -1;


    for(int i = 0; i < 500; i++)
        if( pthread_create(&pool[i],NULL,add,&plus) != 0 )
        {
            perror( "pthread_create failed" );
            pool[i] = 0;
        }


    for(int i = 500; i < 1000; i++)
    {
        if( pthread_create(&pool[i],&minus) != 0 )
        {
            perror( "pthread-create failed" );
            pool[i] = 0;
        }
    }

    for(int i = 0; i < 1000; i++)
    {
        if( pool[i] )
        {
            pthread_join(pool[i],NULL);
        }
    }

    printf("%d",num);
    return 0;
}

在Linux上运行建议的代码会导致:

0
本文链接:https://www.f2er.com/2712520.html

大家都在问