Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4236209
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-05-14 21:37:06

pthread_join 声明:

extern int pthread_join ((pthread_t __th, void **__thread_return));

功能:函数将阻塞调用当前进程,知道该线程退出。
         调用它的进程将一直等待到被调用的线程结束为止。当函数返回时,处于被等待状态的线程资源被回收。成功 0  失败 1

 
描述程序:
      主线程中 create 一个 子线程,子线程中malloc 堆空间,返回
      主线程中修改malloc值

目的:子线程中 malloc 的空间 在主线程中可以访问、修改
        子线程退出时,仅释放私有的栈空间(局部数据)

下面的实验:在子线程中 malloc 中的内容 为 ‘c’,返回到主线程后,修改malloc中的内容 为 ‘d’,显示为 ‘d’

说明:在子线程中的 malloc 堆空间 可以在主线程中使用

代码:
 pthread_exit.rar  

  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>

  5. void *helloworld(char *a);

  6. int main(int argc, char *argv[])
  7. {
  8.     int error;
  9.     int *tmp;
  10.     
  11.     pthread_t thread_id; //typedef unsigned long int pthread_t
  12.      // unsigned long lu 打印输出
  13.     pthread_create(&thread_id,NULL,(void *)helloworld,"helloworld"); //创建线程
  14. //    pthread_create(&thread_id,NULL,(void *)*helloworld,"helloworld"); //创建线程
  15.         //上面的两种方式 都可要编译,而且显示 都是正确的。。怪 了 !!!!!

  16.     printf("*helloworld is %p\n helloworld is %p\n",*helloworld,helloworld);

  17.     if(error = pthread_join(thread_id,(void **)&tmp))//等待子线程退出,保存退出值
  18.     {                      //我们需要注意 &tmp,就是取 tmp占用栈空间的地址
  19.                   // int a[5], &a 也是取的 地址空间地址
  20.         perror("pthread_join");
  21.         exit(1);
  22.     }

  23.     printf("tmp=%p\n*tmp=%d\n",tmp,*tmp); //打印子线程退出的值
  24.     *tmp='d'; //修改该队空间,测试是否可用
  25.     printf("*tmp=%c\n",*tmp); //打印新值
  26.     free(tmp); //释放该段堆空间
  27.     return 0;
  28. }

  29. void *helloworld(char *a)
  30. {
  31.     int *p;
  32.     p = (int *)malloc(10*sizeof(int)); //申请 堆空间
  33.     printf("the message is %s\n",a); //打印 参数信息
  34.     printf("the child id is %ld\n",pthread_self());//打印 子线程 id
  35.     memset(p,'c',10); //设置堆空间信息
  36.     printf("p=%p\n",p); //打印堆空间信息
  37.     pthread_exit(p); //退出线程,将堆空间首地址作为返回值
  38. }

  1. ywx@yuweixian:~/yu/professional/4$ ./pthread_exit
  2. the message is helloworld
  3. the child id is -1216341136
  4. p=0x8fe7098
  5. *helloworld is 0x80486c9
  6.  helloworld is 0x80486c9
  7. tmp=0x8fe7098
  8. *tmp=1667457891
  9. *tmp=d

阅读(1221) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~