Don’t Believe The Lies: PHP Isn’t Thread-Safe Yet

If you took everything you heard for granted, you’d have been lead to believe that the official PHP distributions (from php.net) have been thread-safe since version 5.2.0.

That’s not true. Don’t fall for it. Don’t attempt to use PHP in a multi-threaded environment (mpm_worker on Apache, ISAPI on IIS, etc.), because PHP thread-safety is a myth.. nothing more than a bunch of lies, if you will.

If you look at the PHP download page, you’ll see that the pre-built binaries (in this case, Windows) are split into two: thread-safe and non-thread-safe:

Thread-Safety

The problem is, no matter which you choose, PHP isn’t thread safe. You’ll still get the same, old, dreaded “PHP has encountered an access violation at memory_address” error.

It’s not a question of server configuration so much as it is one of PHP writing bad code and pretending that’s not the case. PHP isn’t multi-threading ready and most everyone knows it… but it seems they still feel the need to pass it off as if it were, never mind the complaints and bug reports that come.

There isn’t a known solution to this problem. The source code for the official PHP distribution is simply not re-entrant and isn’t capable of being used in multi-threaded environments. It’s filled with race conditions and lacks the proper monitors/locks on shared memory spaces (which needn’t be shared in the first place). Unfortunately, there’s not much more to be said; making this post more of a rant than a guiding light for those of you experiencing this issue.

At NeoSmart Technologies we still recommend the only other production-ready, decently-performing *sapi alternative; which is the deployment of PHP by means of the FastCGI protocol. Whether on Linux or Windows, FastCGI scripting engines are considerably faster than their age-old CGI implementations (though the outcome is more-clearly felt on Windows where the CGI model is hideously slow). But we’ve already discussed this before, countless times.

The moral of the story is that PHP isn’t multi-threaded – yet if you go by what they say, you’d come to think it was… until you try it out for yourself and realize that not a darn thing has changed in the 5.2.x releases when it comes to thread-safety and the deployment of PHP in multi-threaded environments.

If you still insist on using ISAPI implementations, you should probably use the latest versions of the PHP4 distribution instead. The older PHP line is less-apt to cause an access-violation error on your machine, and will more than outclass the PHP5 “thread-safe” distributions when it comes to reliability.

PHP needs to clean up their act and either produce real (and verifiably so) thread-safe, re-entrant code or stop the false propaganda that would lead you to believe it’s thread-safe in its current incarnation – especially when most other dynamic scripting languages (such as Perl) have proper, thread-safe engines available.

44 thoughts on “Don’t Believe The Lies: PHP Isn’t Thread-Safe Yet

  1. Yeah, this is so true. More than once I’ve filed a bug report about stability of PHP under multi-threaded environments and it’s been blown-off as a “low-priority, known issue” by the people in charge.

    I notice they don’t explicitly call the first release “thread safe” but slyly lead you to believe so by explictly labeling the second “non-thread-safe” – that’s a dirty trick to play.

  2. It would seem that attaining true thread-safety is going to be critical for PHP’s future. We’ve reached the point today where almost every computer sold has more than one processing core. It’s a huge challenge. I’ve worked on multithreaded development projects since the early 1990s, mostly multithreading old Fortran algorithmic libraries. Today I’m community manager for the Threading Building Blocks open source project — a C++ template library for multithreading applications.

    Multithreading existing code is not easy, so I can certainly sympathize with the PHP developers. But, if your language is not threadsafe, you’re going to fall away as a viable language as we proceed into the multicore future…
     

  3. Thanks for the links, Stephen.

    We’ve looked at a number of alternative PHP processing engines, but haven’t found a stable, reliable, and – most importantly – compatible implementation out there. (The bigger ones are RoadRunner and Phalanger; neither of which work well with the majority of the apps we tested).

    Quercus sounds like a promising solution, I’m testing it now :)

  4. Given this (ant not only) issue and many language defficiencies and problems I’m on my way to switch every simple to moderate project to .NET.
    If there is no acceptable production-safe PHP engine alternative, then you’re better of leaving PHP and begin using some real language.
    It’s a shame a language with almost no reasonable planning and designing behind it has become so widespread and we are stuck to it when it comes to some website that needs to run everywhere.
    Even worse, MS is planning a ‘good’ future for it on Windows. Maybe MS should take control and make it much better.

  5. I finally got around to testing Quercus + Resin; unfortunately the combination’s load times for individual PHP pages is around 110-120% of that for our currently (very finely-tuned) IIS + PHP + FastCGI implementation.

    Perhaps Resin Professional, which stores the compiled PHP opcode instead of acting as a real-time interpreter, would provide a better performance output but the free solution isn’t good enough. :-(

  6. Hi, I think you have something very confused… ‘mpm_worker on Apache, ISAPI on IIS, etc’ are SAPI interfaces. Whether they are threadsafe or not is a matter of how they are coded. The PHP library itself *is* threadsafe.

    This fact can be seen by looking at the source in php-5.2.x/sapi/cgi/fastcgi.c, as well as the rest of PHP’s source tree. If you use PHP via fastcgi on windows, you are using a threaded PHP environment, its that simple.

    However, ff you look at the source of php-5.2.x/sapi/isapi/php5isapi.c you will see that the SAPI does *not* use zends thread safty and is *not* threadsafe. This is a matter of the SAPI, not PHP itself.

    The source for the files above can be viewed via googles code search

    And for what its worth, Quercus is not a PHP implementation, it is PHP emulation. It is a set of Java wrappers to perform php functions. It can be called useful if it does the job that you need, but it is not PHP.

  7. Even if the latest versions 5.3.0 or even older 5.2.10 are not thread-safe?

    Otherwise, I firmly believe that PHP is not built for Microsoft world and even less for IIS and cloudy way to implement it with IIS anyway.

    Apache under Windows could be better solution but could not be reliable enough, don’t you think?

  8. I am quite new to PHP – but I do have a lot of experience with Java. Is the concern that there are no mutual exclusion constructs in PHP? Going through the PHP documentation it looks like there is support for mutual exclusion in PHP 4 and 5 – e.g., the semaphore and shared memory related functions.

    While the language itself does not offer any synchronization or mutual exclusion mechanisms, the library of functions seem to be providing that – this is something similar to (say) C.

    Am I missing something here?

  9. I must admit, that one more time I feel ashamed for the answers I must read and for the time wasted – so to make it a turn I will write about what you made me think, just to justify the time lost. People are so unbelievably underdeveloped, this is real a problem. I totally do not understand why anybody has to argue about the question of PHP beeing Thread safe or not. It is OPEN SOURCE and you can take a look if it is or it is not. Its that simple! Do you argue about the question if a camel can fly? Another simple truth: if you are not able to find the answer yourself in the sourcecode – why are you concerned then anyway? If you are not competent to understand from the sources you can look at, what will it give you somebody telling you “it is threadsafe” or “it is not threadsafe”??? What exactly? A good feeling? Wouldn´t it be the same like somebody givin you a red balloon and telling you “boy, you can fly to the moon with this balloon”- and then making a blog post “i can not fly with the red balloon the guy out there gave me” – what would it feel like?
    But one thing is proven here: incompetent people always are like a magnet for their kind, yuo never get them alone… of course real “xperts” are coming here – guys that run a webserver on Windows – har har! Man, having concerns if your PHP is threadsafe under Windows is like a man wanting to cross the ocean with a camel and beeing concerned about the camel having good sunglasses. no sense. plain stupid.
    Go and THINK, LEARN or leave the brainwork to the people who did already before talking BS.

  10. Please learn basic C++, then comment again, oh Visitor from the future. Unless you have a special gift that allows you to detect un-thread-safe code just like that.

  11. Visitor from The Future, what’s the point?
    You are pointless and worthless in affirmations.

    Present visitor and user

  12. ok all posters especially the delusional future visitor.
    I was looking for a ACTUAL definition of thread safe and non-thread safe.
    I am sorry many here do not think it should matter to someone wanting to install php.
    Maybe they should check into the original of the language PERSONAL HOME PAGE (PHP).
    It was not intended to be convoluted and confusing but simple and easy for all to use.
    We know then difference between 32bit and 64bit programs and why one is better.
    It would appear to me Thread Safe would be best for multi-threaded or mult-processor systems, but honestly i can’t find a understandable explaination. Seems all that exists are opinions on whythings don’t seem to work either way with cgi, fast scripts, IIS, Apache ect. I still am clueless as to why i would choose one over the other.

  13. Ron, give me a bit and I’ll write up a post explaining the differences between the two and the ideal world, when you’d use which of the PHP implementations.

  14. If you want to see what thread-safety can achieve have a look at what TrustLeap did:

    G-WAN is (on average) 120x faster than Apache/PHP (7,000x faster for high-concurrencies).

    http://gwan.ch/en_scalability.html

    And the more CPUs will have cores, the more the gap will widen (in favor to TrustLeap).

    So, the question is not if thread-safety is useful or not but rather if you can afford to use 100x more servers than necessary for the comfort of still using badly designed development tools.

    BTW, Linux and Solaris ports are expected by the end of year 2009… and, ahem, G-WAN is free.

    Now G-WAN is 4-month old, you will not wonder why this is one of the best kept secrets of year 2009.

  15. I think it’s easy for people to show charts and graphs but in real situations, what is worth? G-WAN never heard of it but looks great… on “paper”. All depends on what is compared here!!!

  16. I jumped to the G-WAN site immediately because I’m really looking for a new solution. Unfortunately, it’s a C++ webserver. Don’t get me wrong, I love C++ and all my development is done on it.. But all your graphs that show C++ being the most popular language mean nothing in the web world. We don’t use PHP because we’re choosing to write something, we use PHP because it’s compatible with all the web apps we need. And unfortunately, G-WAN doesn’t even support fastcgi or any other means of getting PHP scripts parsed and loaded externally.

  17. I was seriously concerned there for a moment. Then I realized all you guys are running Windows. Well, I’m still concerned you for you. At least I realized that all this hype is just plain hype.

    Of course you should be using .NET! I mean come on! You’re using Windows for crying out loud. You should use .NET, IIS, MSSQL, and everything from MS. Don’t use code written for a *nix operating system then ported over to Windows and complain that you are having problems. Why is PHP wide spread? Not because Windows is widespread – that’s for sure. It’s because Linux and Apache is wide spread, and because the Personal Home Page author wrote it so long ago.

    So Windows users, go suck and put some more money into MS coffers by buying the latest releases from MS.

    As all the little buys say: LULZ!!!

  18. Hi sims,

    This isn’t a Windows issue. NST is currently running on Linux actually – it’s nothing to do with the platform you use. On Linux, non-multi-threading is “the norm” but if you were to use the PHP multi-threaded binaries, you’d run into the same problem there, too. PHP claims to be multi-thread-safe and isn’t. If you try to run it in a multi-threaded environment – Windows, Linux, Mac, BSD…. whatever – it will crash and burn under load.

  19. Yeah… AFAIK, PHP was developed on Linux. That means processes. Of course it’s going to suck on Windows.

    I mean, PHP doesn’t even have threads. Does it? Last I checked, there was no such thing. Then why run multi-threaded PHP binaries? What kind of gain can you expect *on Linux*? Is it even a good idea to have a PHP run one thread per script, rather than one process per script? If two visitor access a script on a server, what relevance to the two instances’ memory have to each other?

    I agree, PHP does have a way to go – since it doesn’t even have threads. But really, it’s a web scripting language. Heavy stuff can be done in another language. And running it under Windows seems like a bad idea.

  20. Actually, sims, yes it does.

    The PHP-CGI instance can be run in multi-process or multi-thread mode. In general, multi-thread is always better than multi-process but it’s so much harder to develop. On Linux, the performance benefit of multi-thread isn’t that much better than multi-process that by and large, many server applications eschew multi-threading for multi-processing.

    But given that PHP does offer a multi-thread mode, they must do it right. Even worse, when they label their multi-thread packages as “thread-safe” they are purposely misleading their users. It’s a known issue to all PHP developers that PHP isn’t multi-thread safe. If you want to do something, you need to do it right. Either don’t offer multi-thread PHP binaries or offer them and make sure they work.

  21. 100$ agree about doing things correctly. I was just worried that this (in reality) Windows issue was actually affecting me. I was surprised I didn’t have any issues. I understand why. I think the reason why many server applications eschew multi-threading for multi-processing is obvious from a security point of view. Why would one server process need to share any memory with another? This is especially true of PHP. More importantly, if one process dies, it doesn’t affect the others. So it is rather sad that Windows doesn’t implement multi-processes in an efficient manner. Why use Windows in a web server environment anyway? I fail to see the benefit. If you are stuck with an ASP or .NET app that you cannot rewrite, I understand. Any other reason I cannot find.

  22. Hello!

    All of the above comments are wrong.

    A process is a run-time construct executed by a processor.

    A thread is a process w/o memory protection.

    Some web servers use processes, other servers use threads.

    IIS is a threaded web server.
    ZEND, a PHP company has added memory protection to the php library.
    Although it works, it is difficult to program with.

    When Microsoft adopted PHP, they decided to use processes instead of threads, using the Fastcgi SAPI.

    The memory protection added by ZEND is now obsolete and ZEND has dropped support for it.

    Although ZEND dropped it, the code is there and works.

    It doesn’t crash under load, but non-core extensions may not be thread safe and crash the entire HTTP server or write into places they shouldn’t.

    FASTCGI uses processes, not threads.

    Peter

  23. > Sorry Peter, but the core [thread-safe] PHP code is also buggy.

    No, it isn’t. I use it since several years now (Apache mod_php).

    FASTCGI on the other hand is not yet ready for production. A simple fopen(“php://input”) hangs the FCGI instance.

  24. Well, it depends on load. It doesn’t crash under no load, but if you stress it, it will. I don’t know what site you run, but for maybe 3 years or so we ran NeoSmart.net off of mod_php in mpm-worker mode – every time we make slashdot, digg, reddit, etc. we would suffer fatal downtime due to PHP segfaults due to memory corruption.

    Switching to mpm-prefork solved all these issues. And switching to FastCGI after that boosted the performance without sacrificing the quality.

    You say “mpm,” but you don’t mention if it’s prefork or worker mode.

  25. > It doesn’t crash under no load, but if you stress it, it will.

    Well, on windows you don’t have much of a choice. And no, apache mpm_nt doesn’t “crash” PHP.

    > slashdot

    afaik it runs perl, not php.

  26. > getting truly pounded, php would segfault

    I cannot reproduce this. Do you have any special modules enabled? Where does it segfault, what’s the exact error message? Do you have a core dump or something?

    If PHP segfaults or dumps core, please report this bug at http://bugs.php.net

  27. I do not understand. What does ISAPI not doing proper thread sync
    or ODBC not being thread safe have to do with stability issues on Apache/PHP?

    You are spreading FUD …

  28. Peter, “All of the above comments are wrong.” has a greater chance of being a false statement that all of the above comments being wrong.

    As for the PHP-CGI being run in multi-thread mode under linux: What is the benefit? You cannot have threads in your PHP app. That is what I was getting at. So I see no benefit of PHP being multi-threaded. Each request can be it’s own process. This works fine in *nix.

    Windows has it’s own scripting languages. Windows users should be more than happy with that. I have no idea why Mahmoud Al-Qudsi is running PHP on his linux server in mutli-threaded mode. Then again, he did also say he was using IIS. I’m not sure what he’s doing.

  29. Hi sims,

    Actually, we’re now on dedicated Linux servers. But at the time, we wanted to take advantage of a mix of Windows-based scripts and open-source PHP applications, and so we had Windows servers with IIS. Now we’ve migrated all our Windows code to Linux-compatible scripts, and the world is a much better place.

  30. @Mahmoud,

    G-WAN is not written in C++ nor it is using C++.

    G-WAN is written in ANSI C and using ANSI C scripts.

    Yes, scripts, like PHP, Java or C# – just thousands
    of times faster.

    I certainly can understand why you need to re-use
    code from existing Web applications.

    But if you need to scale (and are not willing to
    spend a fortune in staff, floor space, hardware and
    electricity) then it makes sense to use the most
    efficient solution.

    I developed G-WAN for my own needs: as I don’t
    have a fortune to spend but am willing to build
    serious services, I needed something like G-WAN.

    As it did not exist, I created it.

    Now it works on Linux, everybody can see how much
    faster Linux is than Windows.

    My goal was just to mak impossible things become
    possible.

  31. Pierre, you’ve created a good thing and done a great service. I applaud you.

    I hope you did not misunderstand my comments to be in any way demeaning to G-Wan; in fact, I look forward to trialing it for any future projects I work on when I’m looking for a clean, fast, maintainable, and well-designed system.

    My only wish is that some of the existing and already widespread solutions which, as much as we would love them to, aren’t going to go out of use any time soon would also get their act together. I’m sure you appreciate the sheer number of PHP servers/scripts and their users/viewers around the globe – yet this company has the audacity to ignore bugs, refuse to fix issues, and continue to increase the bloat and inconsistency of their platform.

  32. I came here because I was looking for the difference between thread-safe and non-thread-safe PHP builds…and specifically how to determine what my servers are using. I got here because I want to install eAccelerator. To install it as a Zend extension, I need to know how to load it – with or without the ‘_ts’. This will ultimately be going on a production server, so I’ll be installing it twice – once on a test server and then on the production server. But both servers run different versions of Apache/PHP, which will obviously make things more difficult. I want to determine the upgrade path for both boxes to minimize downtime before I do anything.

    As to your actual complaint – PHP is open source. If you see a problem, you can submit patches and fix the issues. I’m on the PHP developer mailing list – mostly to just lurk. Yes, they are rather adamant about not changing certain things, but anything that makes the product more stable is generally accepted and adopted very quickly into the main trunk. And they love patches that work.

  33. There are two things that require intimate familiarity with the codebase before anyone can fix them: thread safety issues and memory leaks. I’m not qualified to fix PHP’s thread safety issues, even though I do that for a living with much more difficult and badly written code as a day job.

  34. sims,

    “”As for the PHP-CGI being run in multi-thread mode under linux: What is the benefit? You cannot have threads in your PHP app. That is what I was getting at. So I see no benefit of PHP being multi-threaded. Each request can be it’s own process. This works fine in *nix.””

    Its not just about if an application programmer can use threads. Its also about the resource usage of the webserver running PHP and if the webserver can reduce that by running PHP scripts inside threads instead of processes. If PHP were thread-safe the webserver could safely share a single copy of the PHP interpreter between multiple threads instead of wasting both memory and CPU cycles to create a complete copy of it for each new subprocess.

    So yes of course each can be run inside it’s own subprocess and that works just fine but it wastes memory and CPU cycles. The benefit of threading is that it wastes less resources allowing a webserver to serve more pages at the same time with the same amount of resources. Threading can also make communication and sharing of data between request handlers more efficient.

    So yes, thread-safe PHP would have its benefits even for Linux regardless of if you could use threads inside your application code or not.

  35. > Unfortunately, there?s not much more to be said

    I don?t understand why instead of just complaining, people who seem to understand the problem as well as this blog posting do not simply offer help to make PHP thread-safe. It is open-source after all, so contributing code (or even forking it) are possible.

  36. Honestly, from years of experience dealing with multithreaded code, I’d rather fully rewrite heavily multithreaded code using sound parallelization techniques to begin with than retrofit/revisit even (or perhaps, especially) millions of lines of code in an attempt at making it threadsafe.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>