Pthread join segmentation fault

428 Views Asked by At

I have the following code where two arrays are modified differently (in one case each element is incremented by 1, and in the other each element is decremented by 1) by two threads. It gives segmentation fault. Could you please point out the error?

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *decrement(void *object){

  int *array = (int *)object;
  for(int i=0;i<5;i++){
    array[i]=array[i]-1;
  }

}

void *increment(void *object){

  int *array = (int *)object;
  for(int i=0;i<5;i++){
    array[i]=array[i]+1;
  }
}
int main(int argc, char const *argv[]){
  int segments = 2;
  pthread_t threads[segments];
  int i;

  int numbers[5] = {1,3,2,9,11}; 
  int numbers1[5] = {0,14,12,4,10};



  int *array;
  array=numbers;
  pthread_create(&threads[0], NULL, increment, (void *) &array);

  int *array1;
  array1=numbers1;
  pthread_create(&threads[1], NULL, decrement, (void *) &array1);
  for(i = 0; i < 2; i++){
      pthread_join(threads[i], NULL);
  }
  for(i = 0; i < 5; i++){
      printf("%d\n", array[i]);
      printf("%d\n", array1[i]);
  }
  pthread_exit(NULL);
}
1

There are 1 best solutions below

0
On BEST ANSWER

Lets take these lines:

int *array;
array=numbers;
pthread_create(&threads[0], NULL, increment, (void *) &array);

Here you pass the address of the variable array to the thread function, but while array itself points to the array, the address of the variable does not.

If you want to use temporary variables, just use the variable by itself:

pthread_create(&threads[0], NULL, increment, array);

Note the lack of cast and lack of address-of operator.

But you don't really need the temporary array variable, as arrays decays to pointers, so you could just do

pthread_create(&threads[0], NULL, increment, numbers);

To illustrate your problem more graphically, what you have is this:

+--------+      +-------+      +---------+
| &array | ---> | array | ---> | numbers |
+--------+      +-------+      +---------+