我正在研究Linux和操作系统中使用的Thread。我在做些运动。目的是对一个全局变量的值求和,最后查看结果。当我期待最终的结果时,我的脑袋震撼了。代码如下
#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;
}
如果我将变量calc作为int * cal放在sum函数中,则i的最终值为25(而不是期望值)。但是,如果我将其作为int calc表示,则i的最终值是10(此练习中的期望值)。当我将变量calc设置为int * calc时,我不知道i的值为25。
胡说叔叔