cgi - 关于php线程安全的问题
PHP中文网
PHP中文网 2017-04-10 14:22:31
0
2
427

http://www.linuxso.com/security/22276...
很多常用的 PHP扩展是以Linux/Unix的多进程思想来开发的,这些扩展在ISAPI的方式运行时就会出错搞垮IIS。

请问这个出错搞垮是怎么做的呢?

PHP中文网
PHP中文网

认证0级讲师

reply all (2)
Peter_Zhu

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

给你举个栗子: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; }

完整的代码阅读笔记可参考 glibc的qsort源码阅读笔记

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

    左手右手慢动作

    Windows中运行PHP建议使用FastCGI方式,不会遇到线程安全问题。

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!