【问题标题】:Can't synchronize more than 2 threads with pthread_mutex_lock不能与 pthread_mutex_lock 同步超过 2 个线程
【发布时间】:2015-05-13 23:13:27
【问题描述】:

所以我正在为我的 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;
}

【问题讨论】:

  • just bugs: 什么意思?
  • 您的索引计算很可能存在问题,导致超出范围的错误。请将您的问题简化为一个最小的示例,然后学习使用调试器。至少几乎可以肯定它不是互斥体本身。
  • d-&gt;vec = vec; 似乎不对。您确定要所有线程处理相同的数据吗?

标签: c pthreads mutex


【解决方案1】:

两个错误

memset(count, 0, 49);

应该是:

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

还有..

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

应该是:

           count[i]++;

【讨论】:

  • 非常感谢,我还以为是互斥体的问题,你帮我清除了。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2020-06-07
  • 2017-02-16
  • 2013-03-18
  • 2017-10-06
  • 1970-01-01
相关资源
最近更新 更多