【发布时间】:2018-05-08 14:31:54
【问题描述】:
我正在研究 Linux 和操作系统中使用的线程。我正在做一个小运动。目标是对一个全局变量的值求和,最后查看结果。当我看到最终结果时,我的心就炸了。代码如下
#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 时,我的值怎么会是 25。
【问题讨论】:
标签: c linux multithreading pthreads