i try to test multithreading in c language and on Manjaro OS. i write a small code but i faced a strange problem
i execute below simple code but i didn't get expected result:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#define THREADS 4
void *routine1(void * x)
{
int result =2;
pthread_exit((void *)result);
}
int main ()
{
int sum=0;
int retval=0;
pthread_t threads[THREADS];
for ( int i=0;i<THREADS;i++)
pthread_create(&threads[i], NULL, routine1, (void *)i );
for (int i=0; i<THREADS; i++)
{
pthread_join(threads[i],&retval);
sum+=retval;
}
printf("%d\n",sum);
return 0;
}
the result of above code is:
2
but i expected to see 8 value on output. after debugging for some hours i found that if i declare the sum variable after pthread_create() function, the code will run normally:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#define THREADS 4
void *routine1(void * x)
{
int result =2;
pthread_exit((void *)result);
}
int main ()
{
int retval=0;
pthread_t threads[THREADS];
for ( int i=0;i<THREADS;i++)
pthread_create(&threads[i], NULL, routine1, (void *)i );
int sum=0;
for (int i=0; i<THREADS; i++)
{
pthread_join(threads[i],&retval);
sum+=retval;
}
printf("%d\n",sum);
return 0;
}
the output of code is:
8
which is right answer.
i want to know why the first code is wrong? it is because of pthread_create() function?
NOTE: if you run this code don't care about warnings, they are all about casting