#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
struct foo {
int a, b, c, d;
}; void printfoo(const char *s, const struct foo *fp)
{
printf("%s", s);
printf(" structure at 0x%lx\n", (unsigned long)fp);
printf(" foo.a = %d\n", fp->a);
printf(" foo.b = %d\n", fp->b);
printf(" foo.c = %d\n", fp->c);
printf(" foo.d = %d\n", fp->d);
} void *thr_fn1(void *arg)
{
struct foo foo = {1, 2, 3, 4};
printfoo("thread 1:\n", &foo);
pthread_exit((void *)&foo);
} void *thr_fn2(void *arg) {
printf("thread 2: ID is %lu\n", (unsigned long)pthread_self());
pthread_exit((void *)0);
} int main(void) {
int err;
pthread_t tid1, tid2;
struct foo *fp;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if (err != 0)
printf("can’t create thread 1:%d", err);
err = pthread_join(tid1, (void *)&fp);
if (err != 0)
printf("can’t join with thread 1:%d", err);
sleep(1);
printf("parent starting second thread\n");
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if (err != 0)
printf("can’t create thread 2:%d", err);
sleep(1);
printfoo("parent:\n", fp);
exit(0);
}
// gcc -Wall main2.c -lpthread -o demo

最后打印的fp的值和第一个线程中初始化的不一样。第一个线程中结构体是个局部变量,函数返回,内存被回收。所以在主线程中就不能访问fp的值。如果想在主线程中获取子线程的值,就要用malloc初始化。

最新文章

  1. JS核心系列:理解 new 的运行机制
  2. 解决Yii2 启用_csrf验证后POST数据仍提示“您提交的数据无法验证”
  3. xutils3
  4. 使用OPENROWSET、Microsoft.ACE.OLEDB实现大数据量的高效导入
  5. CentOS6.5下Tomcat7 Nginx Redis配置步骤
  6. rsync 文件校验及同步原理及rsync server配置
  7. POI Excel导出样式设置
  8. struts2-学习笔记(一)
  9. qml demo分析(customgeometry-贝塞尔曲线)
  10. si_da
  11. [转帖]FORFILES 的简单介绍。
  12. idea使用破解版mybatis plugin插件失败,idea打不开的解决方案
  13. 9-Python3从入门到实战—基础之条件控制语句
  14. Linux中/目录扩容
  15. 撩课-Web大前端每天5道面试题-Day32
  16. 在SQL Server中使用CLR调用.NET方法
  17. 抓取出现时间3s后消失的元素
  18. 阿里云1核1GIIS都装不上
  19. go语言基础之defer延迟调用
  20. 【noip模拟题】最大公约数(数论)

热门文章

  1. 爬虫实践--CBA历年比赛数据
  2. jquery ajax在 IE8/IE9 中无效
  3. C++中对C的扩展学习新增语法——namespace
  4. 通过javascript 执行环境理解她
  5. man 与 help
  6. easyui+ef实现省市区三级联动
  7. Future模式的学习以及JDK内置Future模式的源码分析
  8. ASP.NET Aries 高级开发教程:如何写WebAPI接口
  9. Swoft源码之Swoole和Swoft的分析
  10. Ajax与Http协议