免费注册 查看新帖 |

Chinaunix

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

编写基础的pthread多线程出错,轻帮我分析原因 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-09-14 18:10 |只看该作者 |倒序浏览
本帖最后由 new_new_one 于 2010-09-14 18:12 编辑

小弟刚学多线程编程。写了这样一段代码
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>


  5. void* threadnew(void)
  6. {
  7.         printf("this is %u thread\n",(int)pthread_self());
  8.         pthread_exit(0);
  9. }

  10. int main()
  11. {
  12.         pthread_t pthr1,pthr2;
  13.         if(pthread_create(&pthr1,NULL,(void*)threadnew,NULL)){
  14.                 fprintf(stderr, "error create 1\n");
  15.                 exit(1);
  16.         }
  17.         if(pthread_create(&pthr2,NULL,(void*)threadnew,NULL)){
  18.                 fprintf(stderr, "error create 2\n");
  19.                 exit(1);
  20.         }
  21.         //pthread_join(pthr1,NULL);
  22.         //printf("111111\n");
  23.         //pthread_join(pthr2,NULL);
  24.         //printf("222222\n");
  25.         sleep(3);
  26.         return 0;
  27. }
复制代码
编译执行:
[root@localhost test005]# gcc -lpthread test.c -g
[root@localhost test005]# ./a.out
this is 3086392208 thread
Segmentation fault
[root@localhost test005]#

怎么会出这样的问题,轻大家帮忙看看.

即时我把代码中的那些注释行加上去也是出现:Segmentation fault

论坛徽章:
0
2 [报告]
发表于 2010-09-14 18:32 |只看该作者
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>



  5. void* threadnew(void)
  6. {
  7.         pthread_exit(0); //return 0;
  8. }

  9. int main()
  10. {
  11.         pthread_t pthr1 ;
  12.         if(pthread_create(&pthr1,NULL,(void*)threadnew,NULL)){
  13.                 fprintf(stderr, "error create 1\n");
  14.                 exit(0);
  15.         }
  16.         pthread_join(pthr1,NULL);
  17.         sleep(3);
  18.         return 0;
  19. }
复制代码
更加精简代码,后仍然是段访问异常,我感觉是pthread_exit这行的问题,因为换成return语句后就正常了。

但搞不明白为什么会这样。

pthread_exit()函数可用来终止调用线程。将释放所有线程特定数据绑定。如果调用
线程尚未分离,则线程ID和status指定的退出状态将保持不变,直到应用程序调用
pthread_join()以等待该线程。否则,将忽略status。线程ID可以立即回收。

以上是pthread_exit函数的说明,上面的代码也是很合逻辑的啊,怎么会出错呢。。。。。。大家没遇到这样的问题么?

论坛徽章:
0
3 [报告]
发表于 2010-09-14 19:05 |只看该作者
我找了网上的一个例子
http://hi.baidu.com/abcserver/bl ... aeec6835a80fc4.html

编译执行:
[root@localhost test006]# ./a.out
pthread_detach调用成功!
我是线程,已经开始启动!
pthread_cleanup_push设置完成。
我是线程,即将退出。
Segmentation fault
[root@localhost test006]#

结果仍然是段异常。看来有可能是我的函数库有问题了,也只能这样假设了。都没个人帮忙看看

论坛徽章:
0
4 [报告]
发表于 2010-09-14 19:14 |只看该作者
谢谢大家的关注,问题基本解决了。

我的系统是fc6,所有的工具是默认安装的。
编译运行出了上面的错误。

我刚才开了另一个系统(BT3光盘版), 编译运行就正常了。

哒哒哒,吃饭去咯。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP