title: Synchronize threads in C
body: <p>I'm coding a program for count the "even" numbers of a vector. I enter with a number of threads that must be created to parallelize the analyzing of the vector.</p>
  
  <p>The result always must be 500, but some times It changes (485, 512, 586, 410). I guess the problem is the synchronization of the threads, but I'm using the join, so I don't know why this problem persists.</p>
  
  <p>SOLVED</p>
  
  <p>My code:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;sys/shm.h&gt;
  #include &lt;pthread.h&gt;
  
  #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;
  
          for (j = (i * quantity_positions); j &lt; ((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;
  
    for (i = 0; i &lt; VECTOR_LENGTH; i++)
      vector[i] = i;
  
    threads = atoi(argv[1]);
  
    if (threads &lt;= 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)
      for (i = 0; i &lt; quantity_positions; i++){
        if ((vector[i] % 2) == 0)
          sum++;
      }
    else {
      for (i = 1; i &lt; threads; i++){
        pthread_create(&amp;threads_id[i], NULL, VerifyVector, i);
  
      }
  
      for(i = 1; i &lt; threads; i++)
        pthread_join(threads_id[i], &amp;threads_result[i]);
  
      for (i = 1; i &lt; threads; i++)
        sum += threads_result[i];
  
      for (j = (0 * quantity_positions); j &lt; (quantity_positions + rest); j++)
        if ((vector[j] % 2) == 0)
      sum++;
  
    }
  
    printf("The total is: %d\n", sum);
  
    return 0;
  }
  </code></pre>