c - Can't synchronize more than 2 threads with pthread_mutex_lock -


so i'm doing homework c class , came across problem. want sync acess global array pthread_mutex_lock() seems when 2 or more threads try lock @ same time bugs. here's code:

#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 = 0;     int j = 0;     int count[49];     memset(count, 0, 49);     for(i = 0; < 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; < 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; < num_threads * val; i++)         vec[i] = (int)(rand() % 49 + 1);      for(i = 0; < 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; < num_threads; i++)         pthread_join(threads[i], null);       pthread_mutex_destroy(&mutex);      for(i = 0 ; < 49; i++)         printf("numero %d = %d\n", i+1, numbers[i]);      return 0; } 

two bugs

memset(count, 0, 49); 

should be:

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

and..

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

should be:

           count[i]++; 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -