How To Enable Thread Safety In Php
What is thread safe or non-thread safe in PHP ?

    • Improve Article
    • Save Article
    • Like Article

    Thread-safe: It is used to ensure that when the shared data structure which is manipulated by different threads are prevented from entering the race condition. Thread-safety is recommended when the web server run multiple threads of execution simultaneously for different requests.

    • In Thread Safety binary can work in a multi-threaded web server context.
    • Thread Safety works by creating a local storage copy in each thread so that the data will not collide with another thread.
    • For example: Non-thread-safe: It does not check the safety of the threads which makes it faster to run but at the same time, it becomes more unstable and crashes very frequently.

    It refers to a single thread only builds. In non-thread safe version binaries widespread use in the case of interaction with a web server through the FastCGI protocol, by not utilizing multi-threading. For example:

    • Apache + FastCGI
    • IIS + FastCGI

    So it depends on the way that you want to use PHP. AFAIR running PHP with the fastCGI is the preferable way. If you are unknown which version of PHP is installed in your system then there is an easy way to know that. Check the version of installed PHP Thread safe or Non Thread Safe: Open a phpinfo() and search for the line Thread safety for a thread-safe build you should find enable.

    • On Windows: php -i|findstr “Thread”
    • On *nix: php -i|grep Thread
    • In the both cases will display any one Thread Safety => enabled //or Thread Safety => disabled
    1. Last Updated : 17 Jul, 2019
    2. Like Article
    3. Save Article

    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our & : What is thread safe or non-thread safe in PHP ?

    What is thread safety in PHP?

    This section has details about PHP download locations, and OS issues. Where can I obtain PHP? You can download PHP from any of the members of the PHP network of sites. These can be found at », You can also use anonymous Git to get the absolute latest version of the source.

    • For more information, go to »,
    • Are pre-compiled binary versions available? We only distribute precompiled binaries for Windows systems, as we are not able to compile PHP for every major Linux/Unix platform with every extension combination.
    • Also note, that many Linux distributions come with PHP built in these days.

    Windows binaries can be downloaded from our » Downloads page, for Linux binaries, please visit your distribution’s website. Where can I get libraries needed to compile some of the optional PHP extensions? Note : Those marked with a * are to the best of our knowledge not thread safe; they are not recommended for use in a multi-threaded environment.

    » LDAP (Unix), » LDAP (Unix/Win) : Mozilla Directory (LDAP) SDK » free LDAP server, » Berkeley DB2 (Unix/Win) : » SNMP* (Unix):, » GD (Unix/Win), » mSQL* (Unix), » PostgreSQL (Unix), » IMAP* (Win/Unix), » Sybase-CT* (Linux, libc5) : Available locally. » FreeType (libttf):, » ZLib (Unix/Win32), » expat XML parser (Unix/Win32), » PDFLib, » mcrypt, » mhash, » t1lib, » dmalloc, » aspell, » readline,

    How do I get these libraries to work? You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the ‘configure’ script of PHP (such as the GD library), and others you will have to enable using ‘ -with-EXTENSION ‘ options to ‘ configure ‘.

    Run ‘ configure -help ‘ for a listing of these. I got the latest version of the PHP source code from the Git repository on my Windows machine, what do I need to compile it? See the PHP Wiki for the latest instructions: » Step by Step Build Instructions Where do I find the Browser Capabilities File? You can find a browscap.ini file at »,

    What does thread safety mean when downloading PHP? 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.

    How do I make my code thread-safe?

    What is thread safety ? thread-safety or thread-safe code in Java refers to code that can safely be utilized or shared in concurrent or multi-threading environment and they will behave as expected. Thread-safety is one of the risks introduced by using threads in Java and I have seen java programmers and developers struggling to write thread-safe code or just understanding what is thread-safe code and what is not? Before you learn how to write a thread-safe code you need to understand what is thread-safety and there is no better way to that than looking at a non-thread-safe code.

    • So, let’s see an example of the potential, not thread-safe code, and learn how to fix that.
    • Here is an example of a non-thread-safe code, look at the code, and find out why this code is not thread-safe ? Example 1 public class NumberCounter public int getCountAtomically() } The above example is not thread-safe because ++ (the increment operator) is not an atomic operation and can be broken down into reading, update, and write operations.
    You might be interested:  Air Bags Are Used In The Cars For Safety. Why

    If multiple thread call getCount() approximately same time each of these three operations may coincide or overlap with each other for example while thread 1 is updating value, thread 2 reads and still gets old value, which eventually let thread 2 override thread 1 increment and one count is lost because multiple threads called it concurrently.

    Example 2 public class BasicObservableClass private Set mObservers; public void registerObserver(Observer observer) if (mObservers == null) mObservers.add(observer); } public void unregisterObserver(Observer observer) } private void notifyObservers() for (Observer observer : mObservers) } } In the most general case of multi-threaded environment we shall assume that all methods will be called on random threads at random times.

    The implementation we used for a single-threaded environment is not safe anymore. It is not hard to imagine a flow when two distinct threads attempt to register new Observers at the same time, and end up leaving our system screwed up. One such flow could be (there are many other flows which could break non-thread-safe implementation):

    Thread A invokes registerObserver(Observer) Thread A executes mObservers == null check and proceeds to instantiation of a new setbefore Thread A got a chance to create a new set, OS suspended it and resumed execution of Thread BThread B executes steps 1 and 2 abovesince Thread A hasn’t instantiated the set yet, Thread B instantiates a new set and stores a reference to it in mObservers Thread B adds an observer to the newly created setat some point OS resumes execution of Thread A (which was suspended right before instantiation of a new set)Thread A instantiates a new set and overrides the reference in mObservers Thread A adds an observer to the newly created set

    Despite the fact that both calls to registerObserver(Observer) completed successfully, the end result is that only one observer will be notified when notifyObservers() called. It is important to understand that any of the observers could end up being “ignored”, or both observers could be registered successfully – the outcome depends on the scheduling of threads by OS which we can’t control.

    This non-determinism is what makes multi-threading bugs very hard to track and resolve. There are multiple ways to make this code thread-safe in Java: 1) Use the synchronized keyword in Java and lock the getCount() method so that only one thread can execute it at a time which removes the possibility of coinciding or interleaving.2) use Atomic Integer, which makes this ++ operation atomic and since atomic operations are thread-safe and saves the cost of external synchronization.

    Here is a thread-safe version of NumberCounter class in Java: public class NumberCounter public int getCountAtomically() } Here are some points worth remembering to write thread-safe code in Java, this knowledge also helps you to avoid some serious concurrency issues in Java-like race condition or deadlock in Java: 1) Immutable objects are by default thread-safe because their state can not be modified once created.

    What is the difference between TS and NTS PHP?

    TS and NTS – TS refers to multithread capable builds. NTS refers to single thread only builds. Use case for TS binaries involves interaction with a multithreaded SAPI and PHP loaded as a module into a web server. For NTS binaries the widespread use case is interaction with a web server through the FastCGI protocol, utilizing no multithreading (but also for example CLI).

    What is non thread-safe PHP on Windows?

    What is thread safe or non-thread safe in PHP? In PHP, a thread-safe version of PHP is built with additional constructs to ensure that certain actions are atomic, which means that they are performed in their entirety without any other thread interfering.

    1. This is important in a multi-threaded environment because it allows you to write code that relies on shared states without worrying about race conditions or other synchronization issues.
    2. On the other hand, a non-thread-safe version of PHP does not have these additional constructs and, therefore, cannot guarantee that certain actions will be atomic.

    This means it is unsuitable for use in a multi-threaded environment because multiple threads can interfere with each other’s execution. When choosing which PHP version to use, it is important to consider whether your code will run in a multi-threaded environment.

    Why do we need thread-safe?

    In multithreaded environments, we need to write implementations in a thread-safe way. This means that different threads can access the same resources without exposing erroneous behavior or producing unpredictable results. This programming methodology is known as ‘thread-safety.’

    How do I know if my code is thread-safe?

    How do we know if code is thread-safe? We can tell that code is thread-safe if it only uses and updates shared resources in a way that guarantees safe execution by multiple threads at the same time. Shared resources can be a counter variable, an array, or anything else.

    How do you protect threads?

    HDPE Threaded Plugs – Threaded plugs are an excellent way of ensuring that your threads are protected. They also almost eliminate any risk of the plugs falling out during transport. Typically, you’ll find specific protective plugs based on thread type (JIC, SAE, Metric), and then you’ll want to determine what installation/removal method you want your line to go with.

    What does NTS mean PHP?

    NTS means ‘ None Thread Safe ‘, NTS refers to single thread only builds, NTS does not check the thread safety and do not provides any protection over data access, due to these reason, its works faster to request processing and with this its become unstable and may crashes, NTS used when PHP runs on Fast CGI binary.

    You might be interested:  Which Car Is Best For Safety

    What is the difference between TS and NTS?

    The difference of NTS and TS is in the name itself. TS = Thread Safe. NTS = Non Thread Safe.

    What is PHP difference between PHP4 and PHP5?

    Key difference: PHP a server-side scripting language that has its main implementation in web development. However, it can be used as a general-purpose programming language. PHP4 and PHP5 are two versions of PHP. PHP4 was released on May 22, 2000. On July 13, 2004, PHP5 was released. It was powered by Zend Engine II. It was an improvement over PHP4 and included various new features. – PHP is a server-side scripting language that has its main implementation in web development. However, it can be used as a general-purpose programming language. PHP was originally created by Rasmus Lerdorf in 1995 and it is currently managed by The PHP Group.

    PHP originally stood for Personal Home Page, however it was later renamed. It now stands for PHP: Hypertext Preprocessor, a recursive acronym. PHP is free software released under the PHP License, as is incompatible with the GNU General Public License (GPL) due to restrictions on the usage of the term PHP.

    PHP is an open source, server-side, HTML embedded scripting language. It can basically perform any task that other CGI programs can, but it is mainly used to create dynamic Web pages. Its main advantage is that it is compatible with many types of databases.

    Furthermore, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP. PHP includes a command-line interface capability and can be used in standalone graphical applications. PHP commands can be embedded directly into an HTML source document rather than calling an external file to process data.

    In the HTML document, the PHP script is enclosed within special PHP tags. Due to these tags, the programmer can alternate between HTML and PHP instead of having to rely on heavy amounts of code to output HTML. Also, as PHP is executed on the server, the client cannot view the PHP code. PHP4 and PHP5 are two versions of PHP. PHP4 was released on May 22, 2000. It was powered by the Zend Engine 1.0. After various versions, the last version of PHP4, titles PHP4.4.9 was released in August 2008. After which it was announced that PHP4 will no longer be under development and no more security updates for the version will be released.

    • On July 13, 2004, PHP5 was released.
    • It was powered by Zend Engine II.
    • It was an improvement over PHP4 and included various new features, such as improved support for object-oriented programming, the PHP Data Objects (PDO) extension and numerous performance enhancements.
    • The PDO extension defines a lightweight and consistent interface for accessing databases.

    Late static binding was added in version 5.3. PHP5 was also designed to be backward compatible with earlier versions of PHP and hence should result in little functionality being broken while converting from PHP4 to PHP5. Some differences between PHP4 and PHP5:

    PHP5 removed register_globals, magic quotes, and safe mode. This was due to the fact that register_globals had opened security holes by intentionally allowing runtime data injection and the use of magic quotes had an unpredictable nature. PHP4 was powered by Zend Engine 1.0, while PHP5 was powered by Zend Engine II. PHP5 replaced magic quotes with the addslashes() function in order to escape characters. PHP4 is more of a procedure language while PHP5 is object oriented. In PHP5 one can declare a class as Abstract. PHP5 incorporates static methods and properties. PHP5 introduces a special function called _autoload() PHP5 allows one to declare a class or method as Final PHP5 introduces a number of magic methods, such as _call, _get, _set and _toString In PHP5, there are 3 levels of visibilities: Public, private and protected. PHP5 introduced exceptions. In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference. PHP5 introduces interfaces. All the methods defined in an interface must be public. PHP5 introduces new error level defined as ‘E_STRICT’ PHP5 introduces new default extensions such as SimpleXML, DOM and XSL, PDO, and Hash. PHP5 introduces new functions. PHP5 introduces some new reserved keywords. PHP5 includes additional OOP concepts than php4, like access specifiers, inheritance etc. PHP5 includes improved support of current content management systems. PHP5 includes reduced consumption of RAM. PHP5 introduces increased security against exploitation of vulnerabilities in PHP scripts. PHP5 introduces easier programming through new functions and extensions. PHP5 introduces a new MySQL extension named MySQLi for developers using MySQL 4.1 and later. In PHP5, SQLite has been bundled with PHP. PHP5 introduces a brand new built-in SOAP extension for interoperability with Web Services. PHP5 introduces a new SimpleXML extension for easily accessing and manipulating XML as PHP objects. It can also interface with the DOM extension and vice-versa. In PHP5, streams have been greatly improved, including the ability to access low-level socket operations on streams.

    What makes a program not thread-safe?

    If the code fails when multiple threads execute it from different processes, then, arguably, (the ‘shared memory’ might be in a disk file), it is NOT thread safe!!

    Does PHP have threading?


    • Runtime environments, While both JavaScript and PHP can be embedded directly into HTML, they both need an interpreter in order to run. PHP has long been readily straightforward to install and use, while being powered by the Zend engine. Node.js is a runtime environment for JavaScript on the server side, powered by Google’s V8 JavaScript engine.
    • Concurrency, PHP, like most server-side languages, uses multi-threaded, blocking I/O to carry out multiple tasks in parallel. JavaScript is unique in that it uses a few tricks, namely event loops and Node clustering, to achieve an event-driven, non-blocking I/O execution model that uses a single main thread of execution. PHP is a mature language and has found its own way to achieve asynchronous processing — most notably through the HHVM project released by Facebook.
    • JSON, JSON “JavaScript Object Notation” is a lightweight data format that gives Node.js an edge when dealing with JSON. While PHP can work with JSON, it’s more situational.
    You might be interested:  Why Are Lab Safety Rules Important

    How to check if PHP is enabled?

    Check PHP configuration The easiest way to check the PHP configuration, including which modules are installed, is to create a test script using the phpinfo() function. Open your favorite text editor and type: Save the file as phptest.php in the Web server document root ( /opt/bitnami/apache/htdocs/ for Apache or /opt/bitnami/nginx/html for NGINX).

    How do I know if PHP is 32 or 64 bit?

    Use PHP_INT_SIZE constant – The PHP_INT_SIZE pre-defined constant returns the size of the int that the current PHP is built on, so if it is 8 bytes, then it is definitely 64-bit.

    1 2 3 function is64bitPHP ( )

    function is64bitPHP()

    How to check if a string contains HTTP or HTTPS PHP?

    PHP – Check if String Starts with http – To check if string starts with “http”, use PHP built-in function strpos(). strpos() takes the string and substring as arguments and returns 0, if the string starts with “http”, else not. This kind of check is useful when you want to verify if given string is an URL or not.

    What is the difference between thread-safe and process safe?

    Process-safe refers to program code that can be executed free of concurrency errors by multiple processes concurrently. It is the concept of ‘thread-safe’ applied to processes, where processes are the unit of concurrency instead of threads. Thread safety is a major concern of concurrent programming using threads.

    What is meant by thread safety?

    Thread Safety Multithreaded Programming Guide Thread safety is the avoidance of data races-situations in which data are set to either correct or incorrect values, depending upon the order in which multiple threads access and modify the data. When no sharing is intended, give each thread a private copy of the data.

    Unsafe Thread safe – Serializable Thread safe – MT-Safe

    An unsafe procedure can be made thread safe and serializable by surrounding it with statements to lock and unlock a mutex. shows three simplified implementations of fputs(), initially thread unsafe. Next is a serializable version of this routine with a single mutex protecting the procedure from concurrent execution problems.

    Actually, this is stronger synchronization than is usually necessary. When two threads are sending output to different files using fputs(), one need not wait for the other-the threads need synchronization only when they are sharing an output file. The last version is MT-safe. It uses one lock for each file, allowing two threads to print to different files at the same time.

    So, a routine is MT-safe when it is thread safe and its execution does not negatively affect performance.

    What are the examples of thread safety?

    Examples of thread-safe collections in Java – java.util.concurrent.ConcurrentHashMap, java.util.concurrent.CopyOnWriteArrayList, and java.util.concurrent.BlockingQueue. These collections are designed to be thread-safe, meaning that they can be safely used by multiple threads without the need for external synchronization. For example, a concurrent hash map can be used to store data that is being accessed and modified by multiple threads. The use of a concurrent hash map would ensure that the data stored in it is accessed and modified in a way that is safe and consistent, even when multiple threads are trying to access and modify it simultaneously. It is important to note that while thread-safe collections can help prevent race conditions, they can also come with performance overhead and may not always be the best choice, depending on the specific use case and requirements. It’s important to choose the appropriate collection based on the requirements of the application and the expected behavior of the threads. Here is an example of using a thread-safe collection in Java using concurrent HashMap: import java.util.concurrent.ConcurrentHashMap; public class Example ); one.start(); // Create and start another thread to modify the map Thread two = new Thread(() -> ); two.start(); // Wait for the threads to complete try catch (InterruptedException e) // Print the final state of the map System.out.println(“Final map: ” + map); } } In this example, two threads are created, “one” and “two”, which both modify a concurrent hash map in different ways. The use of a concurrent hash map ensures that the data stored in it is accessed and modified in a way that is safe and consistent, even when multiple threads are trying to access and modify it simultaneously. The threads are started separately and then joined to ensure that both threads complete their execution before the final state of the map is printed.

    What is a thread-safe function?

    A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. In C language, local variables are dynamically allocated on the stack.

    What is a thread-safe language?

    Thread safety – In a thread-safe language, you can access or modify the same memory from multiple threads simultaneously without worrying about data races. This is generally achieved using message passing techniques, mutual exclusion locks (mutexes), and thread synchronization.