Linux如何证明线程共享进程的地址空间

嵌入式技术

1344人已加入

描述

线程

1. 背景

所有的书上都说, 进程中的所有线程共享进程的地址空间 ,如上图中的蓝框都在一个进程中。那么该如何证明这个结论呢?

我只需要在一个线程中访问另一个线程的局部变量就可以了。如果能访问到,那么就证明两个线程是一伙的,如果不能,那 ……不可能。

2. 测试方法

  1. 定义全局指针变量 int32_t *gs_i_ptr
  2. 在线程 a 中定义一个局部变量int32_t run_count = 0,并将其地址赋值给全局变量 gs_i_ptr = &run_count
  3. 在线程 b 中获取全局变量得值 *gs_i_ptr
#include < stdio.h >
#include < stdint.h >
#include < unistd.h >
#include < pthread.h >

static int32_t *gs_i_ptr = NULL;

static void *th1(void *para)
{
    sleep(1);
    while(1)
    {
        printf("th2 run count:%dn", *gs_i_ptr);
        sleep(1);
    }
}

static void *th2(void *para)
{
    int32_t run_count = 0;

    gs_i_ptr = &run_count;

    while(1)
    {
        run_count++;
        sleep(1);
    }
}

int main(int argc, char *argv[])
{
    pthread_t pid = 0;

    pthread_create(&pid, NULL, th1, NULL);
    pthread_create(&pid, NULL, th2, NULL);

    getchar();

    return 0;
}

运行结果:

线程

3. 总结

你看,线程 1 可以访问线程 2 的 局部变量 。它为什么能访问到呢?因为它们两个线程位于同一地址空间!

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分