- What is non thread safe php on windows
- What is thread safe or non-thread safe in PHP?
- 4 Answers 4
- Needed background on concurrency approaches:
- Needed background on how PHP «integrates» with web servers:
- Now, onto your question!
- Final notes
- PHP Thread Safe and Non-Thread Safe for Windows
- 3 Answers 3
- Find if the installed PHP is threadsafe or nonthreadsafe?
- 8 Answers 8
What is non thread safe php on windows
Прелесть open-source кода в его открытости :)) Т.е. при наличии ума/времени/желания можно разобраться, как именно работает программа. Обратная сторона такого кода — сложность в получении нужных скомпилированных пакетов. Например, PHP можно скачать в виде исходников для Nix-систем с последующей компиляцией/сборкой. Для Windows все уже собрано, но готовых бинарных пакетов много! Варианты с «thread safe/non thread safe«, VC6/VC9 и разные версии самого PHP. Статья создана для прояснения ситуации. В основе — разные источники, частично — перевод с английского. Все для того, чтоб в следующий раз мне опять не разбираться — «че к чему!?».
Нужная версия PHP зависит от версии веб-сервера, на котором он будет использоваться. Например, Apache 1.3.x работает с РНР версии 3.0.х, Apache 2.х работает с РНР версии 4.0 и выше. Но это не такая уж проблема, ориентируйтесь на более новые стабильные релизы и то, что стоит у хостера.
Что за приписки VC6, VC9, VC11? Исходники PHP под Windows компилируются в Visual Studio. VC9 получается при компиляции в VS 2008, VC11 — Visual Studio 2012. Соответственно, чтобы все это дело у вас работало, на компе должны быть установлены библиотеки Visual C++ Redistributable for Visual Studio соответствующего года. Некоторые разъяснения по этому поводу здесь.
Кроме того, если web-сервером у вас будет старенький Apache с сайта apache.org, то нужно качать VC6 версии PHP, для компиляции которых использовался Visual Studio 6. Если же PHP будет работать для IIS или в связке с более новым Apache, то можно собрать что-нибудь посовременнее 😉
Для меня главным ступором в выборе служит хостер. Сейчас есть стабильная версия PHP 5.5.4, а у него до сих пор 5.2.17!
Теперь самая интересная часть: «thread safe or non thread safe?»
Вольный перевод статьи Difference between PHP thread safe and non thread safe binaries (Dominic Ryan, 27.09.2007)
Я настолько ломанного английского еще не видел :(( Хотел по-быстрому перевести статью, но с трудом понимаю, что автор понаписал. Постоянные переходы между «what-is-that» и сложно-составные предложения вообще выносят мОСк. Перевод на русский так же осложняется тем, что у меня не хватает знаний и фантазии как правильно по-русски должно называться то, что обычно пишется только на английском %) Например техническое понятие «multi proccess architecture» я ни разу не видел на русском, а мой перл «потоко-небезопасные» вообще под вопросом здравого смысла. Вообщем, что получилось, то привожу.
Разница между thread safe и non thread safe бинарными пакетами PHP
С тех пор, когда PHP впервые появился под Windows 20 октября 2000 года в версии PHP 3.0.17, его бинарные пакеты всегда были собраны как потоко-безопасные (thread safe, TS). Основание следующее: Windows использует мульти-поточную архитектуру работы, а Nix-системы поддерживают мульти-процессовую архитектуру. Если PHP был скомпилирован как мульти-процессовое CGI-приложение вместо мульти-поточного, то его использование в качестве CGI-модуля под Windows на сервере IIS приводит к сильным тормозам и загрузке процессора. С другой стороны, можно подключить PHP на IIS, как ISAPI-модуль (требуется мульти-поточная сборка — прим. переводчика). Тогда возникает другая проблема: некоторые популярные расширения PHP разработаны с ориентиром на Unix/Linux, т.е. с мульти-процессовой архитектурой, что приводит к краху PHP, подключенному на IIS в качестве ISAPI-модуля. Т.о. создание CGI — наиболее стабильная среда для PHP на IIS с основным недостатком, что это ужасно медленно. Приходится загружать и выгружать всю среду PHP из памяти каждый раз, когда есть запрос.
В то время было несколько вариантов для увеличения производительности PHP на IIS. Первый — использовать кеширование опкода программами типа eAccelerator, которые сохраняют PHP-скрипты в частично скомпилированном состоянии на диске и/или в памяти. Такой подход значительно сокращает время выполнения скрипта. Другой вариант заключался в настройке IIS на использование PHP в режиме FastCGI. При этом PHP-процесс после отработки не закрывался, а получал новое задание с очередным php-запросом. К тому же можно было запустить несколько PHP-процессов одновременно, ощутимо ускоряя обработку запросов, что являлось бонусом CGI-режима PHP. При этом могли быть незначительные проблемы с совместимостью PHP-расширений. Это по-прежнему самый быстрый способ использования PHP, и именно на задание такой конфигурации IIS настроен установщик «IIS Aid PHP Installer».
Бинарники, собранные в потоко-небезопасном режиме (non thread safe, NTS), позволяют сконфигурировать IIS (и другие веб-сервера под Windows) на использование PHP, как стандартный CGI-интерфейс с сильным приростом производительности, т.к. в этом случае (в такой сборке) PHP-процессу не нужно дожидаться синхронизации нитей. При сравнении работы «thread safe» и «non thread safe» бинарных пакетов PHP на IIS в качестве стандартного CGI-интерфейса прирост быстродействия составляет до 40%, но это все равно не так шустро как использование опкода в FastCGI методе. А самый большой косяк в том, что нельзя стабильно использовать потоко-небезопасные бинарники вместе с потоко-безопасными. Это значит, что вы не можете использовать системы кеширования опкода типа eAccelerator в среде PHP, созданной потоко-небезопасными бинарными пакетами (утверждение, верное на момент написания статьи).
Если потоко-небезопасный PHP нельзя сконфигурировать до такой же скорости, что и потоко-безопасную среду, то зачем он нужен в такой сборке? Возвращаемся к FastCGI и разработкам Microsoft в этой области за последние несколько лет. Кодеры мелкомягких создали свой вариант FastCGI, который позволяет конфигурировать потоко-небезопасные бинарники PHP в режиме FastCGI, что доводит производительность до скорости света 🙂
Из статьи я сделал вывод, что тормоза наблюдаются только при использовании с веб-сервером IIS. В любом случае, тупняков под Windows+Apache я не видел. В ней же сказано, что можно разогнать NTS-сборку на любом веб-сервере, но я не представляю себе такой конфиг Apache.
Понравилась статья? Расскажите о ней друзьям:
What is thread safe or non-thread safe in PHP?
I saw different binaries for PHP, like non-thread or thread safe?
What does this mean?
What is the difference between these packages?
4 Answers 4
Needed background on concurrency approaches:
Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads — that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes — that is, the web server will create/dedicate a single process for each request.
There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.
Needed background on how PHP «integrates» with web servers:
PHP itself does not respond to the actual HTTP requests — this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is «mod_php». This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.
There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.
You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.
Now, onto your question!
Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment — meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!
At this point, you should be thinking «OK, so if I’m using a multi-threaded web server and I’m going to embed PHP right into it, then I must use the thread-safe version of PHP». And this would be correct thinking. However, as it happens, PHP’s thread-safety is highly disputed. It’s a use-if-you-really-really-know-what-you-are-doing ground.
Final notes
In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!
Speaking only of Unix-based environments, I’d say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn’t use threads, and therefore, PHP thread-safety doesn’t matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won’t have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn’t matter. To see which version your website is using put a file containing on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler .
If you also look at the command-line version of PHP — thread safety does not matter.
Finally, if thread-safety doesn’t matter so which version should you use — the thread-safe or the non-thread-safe? Frankly, I don’t have a scientific answer! But I’d guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!
PHP Thread Safe and Non-Thread Safe for Windows
I am downloading PHP for Windows. I got 2 options on the website.
- PHP Thread Safe
- PHP Non-Thread Safe
Please answer the following questions:
- What is the difference between the two? What are the advantages and disadvantages over one another?
- I am developing an e-commerce website which will have heavy traffic, which one is more recommended and why?
3 Answers 3
From PHP documentation:
Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won’t collide with another thread.
So what do I choose? If you choose to run PHP as a CGI binary, then you won’t need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.
So it really depends on the way that you want to use PHP:
- Apache + LoadModule : Thread Safe
- Apache + FastCGI: Non-Thread Safe
- IIS: Thread Safe
- IIS + FastCGI: Non-Thread Safe
AFAIR running PHP with FastCGI is the preferable way, it performs faster and allows for more fine-grained security configuration.
Find if the installed PHP is threadsafe or nonthreadsafe?
How do I find out whether the installed version of PHP is threadsafe or not thread safe?
Please note that I’m not asking the difference between a threadsafe/non thread safe installation. I would like to find out what is installed currently.
8 Answers 8
Open a phpinfo() and search for the line Thread safety. For a thread-safe build you should find enable.
As specified in the comments by Muhammad Gelbana you can also use:
- On Windows : php -i|findstr «Thread»
- On *nix: php -i|grep Thread
If you prefer to use the command line:
This should give you something like this:
I just find it easier to look at the file named php[version].dll in the root folder of php. Its either php[version].dll or php[version]ts.dll (ts standing for Thread Safe). So, if you have php7.0.10 installed, go to the directory that has this name and you’ll find a file named php7ts.dll. This is a very sad way of finding out, but it works!
Create a new PHP file and insert this code in it:
Then run this page and you will find all of the PHP information. Search for the term that you want, and it will show you it’s enabled.
Then there’s the undocumented ZEND_THREAD_SAFE constant, which seems to exist since PHP 4.3.