免费注册 查看新帖 |

Chinaunix

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

写了个带malloc的多线程程序,不知会不会有问题? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-08-01 21:48 |只看该作者 |倒序浏览
在网上看到malloc函数不是线程安全的,我写了一个多线程程序进行了试验,但好像没有问题,是不是有隐患啊?如果开启的线程多的话,是不是就会出现问题了啊?还有如果想出现问题,我的程序该怎样修改才能证明malloc的线程不安全特性?哪位大侠能否说一下,我现在想通过一个实例来加深对函数的线程安全性与否的理解,我觉得这样更直观,不过本人比较愚笨,举不出合适的例子来,如果大侠们有合适的例子不妨拿出来让小弟参考一下,真是多谢啦!
#include <stdio.h>
#include <pthread.h>
void display(int *i)
{
int j;
char * buf=(char *)malloc(sizeof(100));
printf("address=%u\n",buf);
printf("thread id %d,display value %d\n",pthread_self(),(*i)++);
for(j=1;j<=9999999;j++)
  j=j;
free(buf);
}
int main()
{
pthread_t t1,t2,t3;
int a=1,b=2,c=3;
pthread_create(&t1,NULL,display,&a);
pthread_create(&t2,NULL,display,&b);
pthread_create(&t3,NULL,display,&c);
printf("over in the main thread!\n");
return 0;
}

论坛徽章:
0
2 [报告]
发表于 2006-08-02 10:49 |只看该作者
malloc本身是线程安全的啊。比如你这种情况就是线程安全的。在一个线程里面malloc然后又free掉,就不会有问题的啊。我想他的意思是不是说,将malloc挂到一个全局指针中的时候,然后在线程中使用是不安全的?

论坛徽章:
0
3 [报告]
发表于 2006-08-02 13:07 |只看该作者
POSIX是这么说的:
参见
http://www.opengroup.org/onlinep ... efs/xbd_chap03.html
3.396 Thread-Safe

A function that may be safely invoked concurrently by multiple threads. Each function defined in the System Interfaces volume of IEEE Std 1003.1-2001 is thread-safe unless explicitly stated otherwise. Examples are any "pure" function, a function which holds a mutex locked while it is accessing static storage, or objects shared among threads.


所以,如果你的库是POSIX兼容的,那么就没问题。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP