猿问

使用全局变量的线程问题

我正在研究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。


呼唤远方
浏览 393回答 2
2回答

胡说叔叔

这个问题与线程或全局变量无关,与C的指针算术有关。您可以使用以下代码获得完全相同的结果:int main(){&nbsp; &nbsp; int i = 5;&nbsp; &nbsp; int *j = 5;&nbsp; &nbsp; i = i + j;&nbsp; &nbsp; printf("%d\n", i); // this is 25}这里发生的是,您将指针j分配给值5,并对该指针“加5”。向指针添加5等同于在内存中添加足够的空间来容纳该指针指向的5个对象。在这种情况下,sizeof(int)为4,因此您实际上要添加4 * 5,即20。因此,结果为25,即5 + 4 * 5 = 25。另一个警告是,由于sizeof(int)与机器有关,因此您的结果可能会有所不同。让我再举一个例子,使这一点更加清楚:int main(){&nbsp; &nbsp; int i = 5;&nbsp; &nbsp; uint64_t *j = 5;&nbsp; &nbsp; i = i + j;&nbsp; &nbsp; printf("%d\n", i); // result is 45}由于sizeof(uint64_t)为8,这等效于将5 * 8加上原始值5,因此结果为5 + 5 * 8 = 45。此代码演示了类型转换的许多问题。首先将“ x”声明为“ int”,转换为通用指针“ void *”,然后隐式转换为“ int *”,然后转换回“ int”。正如您已经在此处显示的那样,这些类型的投射肯定会让您脚踩到脚。
随时随地看视频慕课网APP
我要回答