This simple code compiles fine but when I use pthread_join(t1, NULL) it returns segmentation fault (core dump)
int number = 0;
void* change_number(void *x){
printf("helo from some thread\n");
int num = *(int *)x;
printf("%d\n", number);
number += num;
printf("a thread increased the variable by %d\n", num);
}
int main(int argc, char* argv[])
{
pthread_t t1;
pthread_t t2;
printf("1) SUccess code: %d\n", pthread_create(&t1, NULL, change_number, (void *) 5));
printf("2) Success code: %d\n", pthread_create(&t2, NULL, change_number, (void *) 11));
printf("%d\n",pthread_join(t1, NULL));
printf("thread 1 finished\n");
pthread_join(t2, NULL);
}
What is the issue here? I run this in a VM if it has any relevance
>Solution :
As others have noted, your problem is in (void *) 5, this is easily fixed:
int foo = 5, bar = 11;
printf("1) SUccess code: %d\n", pthread_create(&t1, NULL, change_number, (void *) &foo));
printf("2) Success code: %d\n", pthread_create(&t2, NULL, change_number, (void *) &bar));
As noted, you should make the foo and bar variables globals.