无法使用 pthread_mutex_lock 同步超过 2 个线程

标签 c pthreads mutex

我在为 C 类做作业时遇到了一个问题。我想使用 pthread_mutex_lock() 将访问同步到我的全局数组,但似乎当 2 个或更多线程尝试同时锁定时,它就会出现错误。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <string.h>
#include <unistd.h>

#define NUM_THREADS 10
#define VAL 10


int numbers[49];

pthread_mutex_t mutex;


typedef struct {
    int start;
    int* vec;
} dados;

void* threadFunction(void *arg){
    dados* d = (dados*) arg;
    int i = 0;
    int j = 0;
    int count[49];
    memset(count, 0, 49);
    for(i = 0; i < 49; i++){    
        for(j = d->start; j < (d->start + VAL); j++) {
            if(d->vec[j] == i+1)
                count[i] = d->vec[j];
        }
    }

    pthread_mutex_lock(&mutex);
    for(i = 0; i < 49; i++) {       
        numbers[i]+= count[i];  
    }
    pthread_mutex_unlock(&mutex);
    free(d);
    pthread_exit(NULL);
}

int main(int argc, char** argv){
    srand(time(NULL));
    /*=============== Threads ================*/
    pthread_mutex_init(&mutex, NULL);
    pthread_t threads[NUM_THREADS];
    /*========================================*/
    int vec[NUM_THREADS * VAL];
    int i;

    for(i = 0; i < NUM_THREADS * VAL; i++)
        vec[i] = (int)(rand() % 49 + 1);

    for(i = 0; i < NUM_THREADS; i++) {
        dados* d = malloc(sizeof(dados));
        d->start = i*VAL;
        d->vec = vec;
        pthread_create(&threads[i], NULL, threadFunction, d);
    }
    for(i = 0; i < NUM_THREADS; i++)
        pthread_join(threads[i], NULL); 

    pthread_mutex_destroy(&mutex);

    for(i = 0 ; i < 49; i++)
        printf("NUMERO %d = %d\n", i+1, numbers[i]);

    return 0;
}

最佳答案

两个错误

memset(count, 0, 49);

应该是:

memset(count, 0, sizeof(count));

还有..

           count[i] = d->vec[j];

应该是:

           count[i]++;

关于无法使用 pthread_mutex_lock 同步超过 2 个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30226706/

相关文章:

c - dup( fileno( stdin ) ) 然后生成 32 个线程 -> I/O 错误

c - 某些线程返回垃圾值?

c - 以延迟取消结束 pthread

c - 如何使此代码打印 1 2 3 4 5 6

c - getter 方法的互斥量导致死锁

c - 内存延迟曲线问题

c - 递归 strstr 函数

c - fork() 返回正数而不是零

c++ - 只有 5 个并发线程的 Pthread_create 错误 11

mutex - 有没有办法让 Jenkins 的工作互斥?