Im studying Thread's used in Linux and Operating Systems. I was doing a little exercise. The objective is to sum the value of one global variable and at the end look the result. And when I looked to the final result my mind just blow. The code is the following one
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
int i = 5;
void *sum(int *info);
void *sum(int *info)
{
//int *calc = info (what happened?)
int calc = info;
i = i + calc;
return NULL;
}
int main()
{
int rc = 0,status;
int x = 5;
pthread_t thread;
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
rc = pthread_create(&thread, &attr, &sum, (void*)x);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
rc = pthread_join(thread, (void **) &status);
if (rc)
{
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
printf("FINAL:\nValue of i = %d\n",i);
pthread_attr_destroy(&attr);
pthread_exit(NULL);
return 0;
}
If I put the variable calc in the sum function as int *cal then the final value of i is 25 (not the expected value). But if I put it as int calc then the i final value is 10 (my expected value in this this exercise). I dont understand how can the value of i be 25 when I put the variable calc as int *calc.