multithreading - Synchronize threads in C -


i'm coding program count "even" numbers of vector. enter number of threads must created parallelize analyzing of vector.

the result must 500, times changes (485, 512, 586, 410). guess problem synchronization of threads, i'm using join, don't know why problem persists.

solved

my code:

#include<stdio.h> #include<stdlib.h> #include<sys/shm.h> #include <pthread.h>  #define vector_length 1000  int vector[vector_length]; int sum = 0; int quantity_positions;  void verifyvector(int i){     int j = 0;     int vector_sum = 0;          (j = (i * quantity_positions); j < ((i + 1) * quantity_positions); j++)       if ((vector[j] % 2) == 0)         vector_sum++;     //printf("thread num %d sum value: %d\n", i, vector_sum);         pthread_exit(vector_sum); }  int main(int argc, char*argv[]){   int i, j;   int threads = 0;   int rest = 0;    (i = 0; < vector_length; i++)     vector[i] = i;    threads = atoi(argv[1]);    if (threads <= 0)     threads = 1;    int threads_result[threads];    pthread_t threads_id[threads];    quantity_positions = vector_length / threads;    if ((quantity_positions * threads) != vector_length)     rest = vector_length - (quantity_positions * threads);    if (threads == 1)     (i = 0; < quantity_positions; i++){       if ((vector[i] % 2) == 0)         sum++;     }   else {     (i = 1; < threads; i++){       pthread_create(&threads_id[i], null, verifyvector, i);      }      for(i = 1; < threads; i++)       pthread_join(threads_id[i], &threads_result[i]);      (i = 1; < threads; i++)       sum += threads_result[i];      (j = (0 * quantity_positions); j < (quantity_positions + rest); j++)       if ((vector[j] % 2) == 0)     sum++;    }    printf("the total is: %d\n", sum);    return 0; } 

pthread_join() not magic. it's not synchro mechanism should use protect data fro multiple access. not seem think need.

furthermore, don't need synchro anyway since not mutating vector during run of threads.

what need fix bugs outlined in molbdnilo/my comments. stop using confusing i,j,k single-letter vars , don't use global vars unless need to. fix array-indexing.

i don't understand 'parent process' stuff:(


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -