免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3926 | 回复: 1
打印 上一主题 下一主题

[其他] C++ pthread_create 內存空間問題 [复制链接]

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:49:03
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2018-03-24 14:15 |只看该作者 |倒序浏览
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <pthread.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7. #include <sys/types.h>
  8. #include <sys/syscall.h>

  9. pid_t gettid()
  10. {
  11.     pid_t tid;
  12.     tid = syscall(SYS_gettid);
  13.     return tid;
  14. }

  15. class B
  16. {
  17. public :
  18.     int data;

  19.     B()
  20.     {
  21.         data = 100;
  22.     }

  23.     static void* print(void* __this)
  24.     {
  25.         B * _this =(B *)__this;
  26.         while (1) {
  27.             printf("print pid=%d, tid=%d, data=%d\n", getpid(), gettid(), _this->data);
  28.             sleep(1);
  29.         }

  30.         pthread_exit(NULL);
  31.     }

  32.     static void* add(void* __this)
  33.     {
  34.         B * _this =(B *)__this;
  35.         while (1) {
  36.             _this->data += 1;
  37.             printf("add pid=%d, tid=%d, data=%d\n", getpid(), gettid(), _this->data);
  38.             sleep(2);
  39.         }

  40.         pthread_exit(NULL);
  41.     }

  42.     void start_thread()
  43.     {
  44.         pthread_t thread_add, thread_print;
  45.         pthread_create(&(thread_print), NULL, print, (void*)this);
  46.         pthread_create(&(thread_add), NULL, add, (void*)this);
  47.     }
  48. };

  49. int main(int argc, char* argv[])
  50. {

  51.     B b;
  52.     b.start_thread();

  53.     while(1) {
  54.         printf("main pid=%d, tid=%d, data=%d\n", getpid(), gettid(), b.data);
  55.         sleep(3);
  56.     }




  57.     return 0;
  58. }
复制代码


我了解是 thread 在 stack 宣告的變量都是每個 thread 各自獨立

只有是 global 變量屬於 .data 跟 heap 是 process 裡面所有thread 共享

那我疑問是在上面網址程式裡面 main() 函數宣告一個 B class 的 instance b 變量

那這塊instace 應該是屬於 stack 不是 heap(因為我不是new 出來的)

那我之後呼叫 b.start_thread();

產生兩條thread 在 member function add / print  還有 main 函數都用  while(1)

不斷印出data 跟 pid & tid , 看起來 class 的 data變量 是共享的~

那我不懂是 B b; 宣告出來的 b 應該屬於 stack ,

在同Process 底下的不同 thread 怎麼能夠存取在 stack instace ?

謝謝

论坛徽章:
324
射手座
日期:2013-08-23 12:04:38射手座
日期:2013-08-23 16:18:12未羊
日期:2013-08-30 14:33:15水瓶座
日期:2013-09-02 16:44:31摩羯座
日期:2013-09-25 09:33:52双子座
日期:2013-09-26 12:21:10金牛座
日期:2013-10-14 09:08:49申猴
日期:2013-10-16 13:09:43子鼠
日期:2013-10-17 23:23:19射手座
日期:2013-10-18 13:00:27金牛座
日期:2013-10-18 15:47:57午马
日期:2013-10-18 21:43:38
2 [报告]
发表于 2018-03-26 09:12 |只看该作者
你的thread中是B *,都指向main中的b,同一进程中当然可以访问到
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP