php+linux+线程安全,关于php线程安全的问题

如果没有对多线程做特殊处理的话,任何会带来副作用的函数内都可能导致这个问题。

给你举个栗子:glibc的qsort函数在多线程使用的时候也可能会core。为什么呢?因为有一段代码是这样的if (phys_pages == 0)

{

phys_pages = __sysconf (_SC_PHYS_PAGES);

//__sysconf函数在sysdeps/posix/sysconf.c中

//_SC_PHYS_PAGES对应到函数__get_phys_pages()

//位于文件sysdeps/unix/sysv/linux/getsysstats.c中

//通过phys_pages_info()打开/proc/meminfo来读取内存信息

//(这就定位到了qsort打开文件的问题)

if (phys_pages == -1)

/* Error while determining the memory size. So let's

assume there is enough memory. Otherwise the

implementer should provide a complete implementation of

the `sysconf' function. */

phys_pages = (long int) (~0ul >> 1);

/* The following determines that we will never use more than

a quarter of the physical memory. */

phys_pages /= 4;

pagesize = __sysconf (_SC_PAGESIZE);

}

//注意,上面这一段if会产生竞争,出现线程安全安全:

//如果两个线程都调用qsort,当线程1获取了phys_pages之后,线程2

//才到达if,线程2就会跳过这一段代码,直接执行下面的if语句——

//而此时pagesize尚未初始化(=0),于是就会出现除零错误,导致

//core dump

/* Just a comment here. We cannot compute (phys_pages * pagesize)

and compare the needed amount of memory against this value.

The problem is that some systems might have more physical

memory then can be represented with a `size_t' value (when

measured in bytes. */

/* If the memory requirements are too high don't allocate memory. */

//如果所需的内存页数大于总的可用内存,则不分配内存(防止swap降低性能)

if (size / pagesize > (size_t) phys_pages)

{

//直接使用stdlib/qsort.c中的 _quicksort 进行排序

_quicksort (b, n, s, cmp, arg);

return;

}

顺便提一下,解决qsort问题的办法,是在主线程中先调用一次qsort,让它初始化了pagesize,这样只会就不会遇到竞争了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值