Linux如何證明線程共享進程的地址空間

2023-08-25 16:10:40 來源:大川搬磚


(資料圖片)

1. 背景

所有的書上都說, 進程中的所有線程共享進程的地址空間,如上圖中的藍框都在一個進程中。那么該如何證明這個結論呢?

我只需要在一個線程中訪問另一個線程的局部變量就可以了。如果能訪問到,那么就證明兩個線程是一伙的,如果不能,那 ……不可能。

2. 測試方法

定義全局指針變量 int32_t *gs_i_ptr;在線程 a 中定義一個局部變量int32_t run_count = 0,并將其地址賦值給全局變量 gs_i_ptr = &run_count;在線程 b 中獲取全局變量得值 *gs_i_ptr;
#include < stdio.h >#include < stdint.h >#include < unistd.h >#include < pthread.h >staticint32_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 的 局部變量。它為什么能訪問到呢?因為它們兩個線程位于同一地址空間!

標簽:

上一篇:Linux如何獲取進程的基地信息
下一篇:最后一頁