113 Responses

  1. Multithreading in php | PHP-Blog.com
    Multithreading in php | PHP-Blog.com at |

    […] the original: Multithreading in php Related ArticlesBookmarksTags PHP PHP is a computer scripting language. Originally […]

  2. Raul
    Raul at | | Reply

    Thanks! 😉

  3. Raul
    Raul at | | Reply

    Unfortunatelly “live” , “at work” no because of M$ OS.
    But i’ll use it for my scripts in Ubuntu! 😉

  4. upsemshop
    upsemshop at | | Reply

    Hi guys,
    My PC worked not correctly, too much mistakes and buggs. Please, help me to fix buggs on my computer.
    My operation system is Win Vista.

  5. Joey
    Joey at | | Reply

    At line 170, there is an error.

    pcntl_waitpid( $this->pid, $status = 0 );

    You never use the variable $status anyway, so it doesn’t hurt. But if you ever decide to use the $status variable, passing in $status = 0 does not pass the variable to the function, it passes the value of the assignment, 0.

    If you set your error reporting to strict, it will complain that:

    “Only variables should be passed by reference”

    Otherwise, thanks for sharing your code. :)

  6. Joey
    Joey at | | Reply

    Why do you want to pass a zero in there? That parameter is not expecting a _value_, it’s expecting a _reference_. PHP can can put the real status value in it and give it back to you so that you can check against it later.

    See the functions pcntl_wif*()

    I hope that made sense.

  7. George
    George at | | Reply

    Thanks for the example code. Any idea how I would use that in an Apache server that executes PHP scripts? I’m on Ubuntu and it seems as if pcntl_fork() is not available in the PHP that is in the apache. I tried the solution in


    but it does not seem to work for me.

    Any ideas?



  8. Zoli
    Zoli at | | Reply


    The function I’d like to thread returns a string, is it possible to retrieve that somehow and let them set in a result array in the main code starting the threads for example?

    Thanks in advance, Zoli

  9. sims
    sims at | | Reply

    Thanks for that. I learned a lot from your code. A suggestion to an otherwise excellent class:

    It is allowed for the first parameter of call_user_func_array to be an array(class, ‘method’). So, there is a problem with function_exists in runnableOk. Besides, if it is_callable then function_exists. So I don’t think you need to check both.

  10. Ricardo Sanchez
    Ricardo Sanchez at | | Reply

    Hi! Great script!

    I’ve been testing the Zoli idea and the “return” aproximation and it does not work… mainly because the child dies and there is no communication between parent and child…

    They are two separated processes, so… any idea to get returned data to the parent from the children function? Maybe sockets??

  11. Ricardo Sanchez
    Ricardo Sanchez at | | Reply

    Hi! I’ve found how to return data from child to parent, using pipes:

    In class Thread:

    In function which uses Thread:

  12. Shane Mc Cormack
    Shane Mc Cormack at | | Reply

    Further to the above, I was mistaken, that obviously doesn’t work, all it does is stop the warnings.

    It only appeared to be working based on the input I was testing with, oh well.

  13. Shane Mc Cormack
    Shane Mc Cormack at | | Reply

    I needed to pass a value by reference to the “threaded” function and noticed that in its current instance, this class only passes by ref, this was changed near line 147 by using:

    I’m not sure of the performance hit by doing this, but it works.

  14. Jelle De Loecker
    Jelle De Loecker at | | Reply

    The threading itself worked like a charm, unfortunately my singleton mysql wrapper wouldn’t work with it as it always complained about the database going away.

  15. [PHP-mencoder] Des filigranes (watermark) dans vos flv avec PHP et mencoder « Emilien DAMART

    […] l’ai donc réécrit en PHP en utilisant cette classe qui permet de gérer des threads (Attention, celle-ci utilise l’extension pcntl de PHP). […]

  16. Steponas
    Steponas at | | Reply

    Thanks for the great class! This has helped me with the question “What should I use for my PHP project as a command-line multithreaded net app: Python or Java”. I’ll go all the way with PHP.

  17. Mark
    Mark at | | Reply

    Thanks for this, I’d like to suggest an addition. I needed to call a method in a class, but runnableOK was returning false as a method isn’t a function… So, assuming i’m passing the object instance and method name in an array like this: $t = new Thread(array($this, ‘publicmethod’)), the following change will allow it.

    just make sure the method isn’t private! Or, instead of passing the object, you could modify it to accept the class name.

  18. Tim
    Tim at | | Reply


    Seems like a very nice class, and I’ve tried to implement it into an IRC bot written in PHP, but I can’t get it to work properly without the bot dying. After trying Ricardo’s pipe trick, i got a bit further, well the bot doesn’t die after execution, but doesn’t open the pipe either.

    I wanted to try to implement some sort of threading mechanism, because the bot might have to execute some heavy commands every now and then, that is – commands which consumes a great amount of time (i.e. a ping command), which stalls the but while executing – so my thoughts were, launch the command in a new thread, and write back the reponse (when done) to the user/channel – while being able to make the bot do other tasks, while processing.

    Any ideas? or is this just not possible?


  19. PieterMX
    PieterMX at | | Reply

    Nice class, added a few lines to support static functions in objects:

  20. Daniel Pötzinger
    Daniel Pötzinger at | | Reply

    Thanks for sharing this! Inspired by your work I published Threadi today.

  21. mr_mojtaba
    mr_mojtaba at | | Reply

    Hi .
    I want to use this class in my php code in Ubuntu. but i dont know why it not worked here.
    When i run the project:

    This message is shown:
    Threads not supported
    How can i solve this problem?

  22. mr_mojtaba
    mr_mojtaba at | | Reply

    how can i check the pnctl library is installed? Please describe me what do i do to use this class?
    Do i use this class(Thread.php) in windws os?

  23. mr_mojtaba
    mr_mojtaba at | | Reply

    I need multithreading to do some work.Please help me how i can use this class. I write the frist example of this page, but i dont have the problem: ‘Threads not supported’
    How can i check pnctl library is installed? How can i?
    With Regards.Mojtaba

  24. mr_mojtaba
    mr_mojtaba at | | Reply

    Thanks very much

  25. mr_mojtaba
    mr_mojtaba at | | Reply

    I have a question about using threading in php:
    I need to check some conditions in my code and if the conditions were true then insert some information to mysql database and redirect the user to other pages. I dont like the user wait so that the informations is recorded to database and then redirect to other pages. Do i can insert information to my database as threading?
    If i use this code at the end of my code: While(t1->isAlive()){}…
    Then the user should be waiting so that transaction is compeleted and then redirect. So How can i solve this problem?
    With Regards.Mojtaba

  26. Diego
    Diego at | | Reply

    Hi Tudor, greetings from Ecuador…. I’ve tried your code sending simple parameters to start function (integer and string values) but if I use complex objects I cannot reach functions from my nested variable in the object…. I’m not sure if it is clear…

    Thanks so much in advance for the help you could provide me…

  27. Marines MUD – W pogoni za RAMem
    Marines MUD – W pogoni za RAMem at |

    […] już szczęśliwym posiadaczem ubuntu, nie stanowi to żadnego problemu. Znalazłem też w sieci fajną klasę, która umożliwia czytelniejszą obsługę wątków w obiektowym stylu. Dzięki tej klasie obsługa wątków jest dziecinnie prosta. Autor zamieścił przykłady jej […]

  28. Kailash
    Kailash at | | Reply

    hi Tudo,

    I need urgent help in this. I am trying to use your thread.php ro read multiple file but when i call processImage function then it does not come back to main function. Its not going to second loop to read files. Just hangs there itself.

    CAn you guide me.


  29. Lea Hayes
    Lea Hayes at | | Reply

    Hello Tudor,

    What benefits are there to emulating multi-threading in PHP?

    Don’t get me wrong, you have come up with a working thread emulation, but what does it actually achieve?

    The emulation will incur overhead, but the “threads” will not be assigned to separate processors by the OS. If anything using emulated threads is only going to slow an application down (as opposed to boosting performance).


  30. Prozessorauslastung fällt während Skript läuft (unter Ubuntu) - php.de

    […] die skripten multithreaded laufen lasse: hierbei verwende ich einen wrapper für pcntl_fork() (vgl.HIER). das skript erzeugt damit für die ersten 5-10 sekunden vollast auf allen 8 threads (oder sovielen […]

  31. How To “Find And Replace” Words In Multiple Files In a Folder : Ranjith Siji – Programming the Web

    […] via their port numbers (baibhavsingh.wordpress.com)You’ve Been Hacked! (famousbloggers.net)Thread class for multithreading in PHP (motane.lu)How do I increase upload file limit from 2MB to 10MB under Apache 2 UNIX / Linux web […]

  32. Asynchrone Threads in PHP - php.de
    Asynchrone Threads in PHP - php.de at |

    […] danke für den Hinweis. War nur durch das drauf gekommen -> Multithreading PHP Script läuft jetzt auch ganz gut ohne das ganze, aber kurze Frage noch. Wird bei PHP-Code: […]

  33. Jack
    Jack at | | Reply

    I just needed a help regarding multithreading in php.So i visited it.
    I follow up the source code of multithreading.but in the source m having an error.
    [code lang=”php” 1=”[/code” language=”Thread::available()”][/code]
    Im having problem in the above line.Can anyone help me out ?


  34. O Senhor do PHP: A Irmandade dos Scripts | LordFokas.com – Blog

    […] Outra coisa brutal que me apercebi, é que dá para fazer MultiThreading com PHP, através de uma classe implementada por um individuo cujo nickname é Tudor. Podem aceder ao seu blog e ter acesso a mais especificações sobre a classe Thread() aqui: http://blog.motane.lu/2009/01/02/multithreading-in-php/ […]

  35. cojack
    cojack at | | Reply

    Tudor do you have any idea how to create a shared memory between forks? Im realy newbie in this topic 😉


  36. Gdhami
    Gdhami at | | Reply

    Thanks for the code, much appreciated!

    I’ve been trying to run a modified version of the 2nd example on my box, it works, but somewhere after executing the threads it stops if I enable the sleep(1); call *or* if I use this line

    Changing while to if fix the problem but well the logic is then broken.

    The code is here, I’d be infinitely grateful if you can shed some light on it:

    Thanks in advance,

  37. Linkdump #52: ABC PHP. « Tomasz Kowalczyk

    […] Multithreading in php. Trochę na temat wielowątkowości w PHP. […]

  38. jost125
    jost125 at | | Reply

    Hi, I was thinking about something very similar, so thanks for saving my time :-)

    I have one note, the name is not picked right. Lot of people might be confused, because parallelism via processes is very different than via threads. Threads have shared memory, are run in one process and so on.

    So much more suitable name should be Process.

    Still thanks for the work!

  39. Bruno
    Bruno at | | Reply

    is there a sollution for windows system?

  40. Better Convert pdf to Multiple jpg | Dalibor Sojic

    […] By default, PHP has no built-in support for multithreading, but Tudor Barbu has developed multithreading class for PHP. […]

  41. Netbeans Code Templates | The Playabl Blog

    […] to make the page load more quickly, I can use a template with the code I found on this PHP Multithreading site. Share […]

  42. sa
    sa at | | Reply

    is there a sollution for windows system?

  43. Why is realtime apps for php such a problem? - Quora

    […] level support, there is a guy who created a class which mocks the JAVA Threading here is the link: http://blog.motane.lu/2009/01/02…This answer .Please specify the necessary improvements. Edit Link Text Show answer summary […]

  44. Cosmin
    Cosmin at | | Reply

    If you are talking about Windows, in most of the cases the discussion involves .NET. Of course..you can achieve multithreading by interoping with Java, C++ etc., but since .NET always come in handy for me, I can recommend you this http://www.facebook.com/note.php?note_id=281965971827784

  45. Suresh
    Suresh at | | Reply

    Thanks for your information

    how to use this for search?
    search result will execute same window but override previous one

  46. Cosmin
    Cosmin at | | Reply

    My post is about achieving multithreading in general, not on a specific case. Of course, you are limited to the single main thread of PHP but which can spawn multiple child threads by interoping, for example, with .net.

    You can think of it like this: PHP thread would pass a list of “operations” to be executed on different threads by .net. Instead of having them waiting one for eachother, they could run in parallel. Of course, you can not overcome the limitation of the PHP thread, but there is still a slight gain on performance.

  47. Marian
    Marian at | | Reply

    Why use the loop to keep things alive?
    You can just set the time limit to 0 and only when one thread closes you can check if there are any other working if not exit.
    I think you might spare some resources.
    I am working a lot with socket listeners built in PHP and Python… so they are never supposed to stop and the PHP version works very neat like that using quite few resources.

  48. anon
    anon at | | Reply

    what just writing a plugin for sonic daemon?

  49. victor wallin
    victor wallin at | | Reply

    what do you think about this solution? (Runs on Linux (slackvare)

    PHP 5.2.11 (cli) (built: Oct 2 2009 17:30:20)

  50. Fizzadar
    Fizzadar at | | Reply

    Awesome! There’s hardly any good implementations of forking in php available online, and this one is definitely the best!

  51. J. Bruni
    J. Bruni at | | Reply

    Very nice! Thanks for sharing.

  52. Sanjoy
    Sanjoy at | | Reply

    Hi !!!
    I am trying to use this above example. I am working in WAMP. When i am running the Parallel-Returnable.php file its shows Fatal error: Class ‘Threadi_Thread_NonThread’ not found

    And i want to know how to enable pcntl in WAMP ?
    Please help me to solve this.

    WIth Thanks & Regards,

  53. PHP multithreading through .NET interop « PHP / Zend / www.elcome!

    […] For Unix we have http://www.php.net/manual/en/intro.posix.php and http://www.php.net/manual/en/intro.pcntl.php which are a set of complementary libraries that allows process manipulation operations. Let me repeat that: “process manipulation operations”… since there is nothing mentioned about threading, you can simply put it this way: PHP doesn’t natively support threading in Unix through the libraries mentioned above, instead it supports process forking. As you may already noticed, I used the term of “natively” because you can achive multithreading by interoping with languages like Java, C / C++ or even .NET through Mono. If you may wonder what are the advantages of using threads over processes in general, read this http://www.programmerinterview.com/index.php/operating-systems/thread-vs-process/; in particular, each language can have it’s own mechanisms of dealing with threads. A nice article on “multithreading” in PHP can be found on my comrade’s blog Tudor a.k.a. motanelu http://blog.motane.lu/2009/01/02/multithreading-in-php/. […]

  54. dTrane
    dTrane at | | Reply

    Hello they call me Gabe I love handbags and all kinds of other things as well!

  55. Julio Araya
    Julio Araya at | | Reply

    Wanna use objects and his methods or static methods?

    Step 1: Change the method Thread::runnableOk to this:

    Step 2: Use this code to use you objects


  56. [PHP] Listener
    [PHP] Listener at |

    […] […]

  57. Pointless Ramblings
    Pointless Ramblings at |

    […] An example daemon is listed below, the class requires the PHP pcntl extension (*nix only) & Tudor Barbu’s excellent Thread class → […]

  58. Damian
    Damian at | | Reply

    I did some of php coding for electriccars4kids.org
    Thank you for sharing!

  59. Lorin
    Lorin at | | Reply

    Regarding threading and MySQL (or probably any database server), here are my findings which might help someone else. Generally, launching a new thread “duplicates” all the variables and memory contents of the parent and your child starts with all of it as “baggage”. This includes your current connection to MySQL. As long as your parent (or a second child) doesn’t use that connection, you can use it from your child without any problems. If you have multiple children using the database, each child should open it’s own connection (that kind of makes sense).

    However, PHP screws you as soon as your first child ends. As we know, PHP automatically closes connections to MySQL once a script (e.g. your child) ends. This unfortunately includes the connection the child inherited initially from the parent. This means that as soon as one of your child processes has ended, your parent process will have to reconnect to MySQL in order to do anything with the database – or you will get the “MySQL has gone away” error.

    In order to keep connections clearly assigned to each thread, I recommend to:
    – open one new connection per child
    – store the connection resource in a variable and always the identifier for any mysql_* commands. If you use mysqli, use the object oriented aproach and create a new mysqli-object for each thread.
    – remember that your parent’s mysql connection will be broken as soon as the first child process has ended. your parent will need to reconnect to MySQL.

  60. Max
    Max at | | Reply

    I like you simple implementation, I see many threads in my task manager after running your script. I found on Git hub similar project which work better for me. https://github.com/kulikov/php-threads-manager

  61. Chey
    Chey at | | Reply

    For those interested in parallel processing you can check out Gearman. Works with PHP.


  62. Simon
    Simon at | | Reply

    Hi Tudor
    This is a great function you have build. It’s easy to use and work very well.
    Is there a build-in function to limit the number processes that runs at the same time? Or have you thought about building it in. I have for example perhaps 500000 loops through some data, that I want to spread out on multi processes, but of course I suppose it will not be good to start 50000 processes at the same time?! Or is there something build into PHP that ensures it doesn’t start to many at the same time?

  63. No Threading In Shared Servers « The Playabl Blog

    […] have the cheapest plan in Dreamhost, which is the Shared Server plan. I tried testing Tudor Barbu's Thread class to see if I could get my site to multi-thread in order to produce pages as quickly as […]

  64. Php script issue, syntax error | question code

    […] this one specific threading system i found in php, but it gives a error on index = 0;, any ideas? http://blog.motane.lu/2009/01/02/multithreading-in-php/ any help is appreciated. and i attached the link to the thread script of course, and thats about […]

  65. Gerben Wijnja
    Gerben Wijnja at | | Reply

    Hmm, I expected my code to be recognized, but it’s not syntax highlighted. Can’t find any pointers on how to post code, so here goes another try with [ code ] tags.

    I made some code style improvements:

    • Made all the code PHP CodeSniffer compatible.
    • Fixed return type of kill() from ‘boolean’ to ‘void’. Stop() returns void, so kill() will also return void.
    • Removed underscores from local variables. Only private class variables should be prefixed with an underscore.
    • Changed function name available() to isAvailable() – function names should always start with a verb.
    • Changed function name runnableOk() to isRunnableOk() – same reason
    • Changed function name signalHandler() to handleSignal() – same reason

  66. redknight101
    redknight101 at | | Reply

    How can I include max number of process?

  67. smith
    smith at | | Reply

    Hi Tubo,

    Your code is very clear.. i tried the example in shared hosting.
    This script only runs the first thread…
    Can you help me how to do this??

  68. Zizaco
    Zizaco at | | Reply

    Amazing class man. Thank you! I will post an article about it in my blog soon.
    I’ve done some “pipeing” using Memcached. Now this:

    …works like a charm. (:

  69. Same PHP script is showing different output in browser than when it’s run from command line

    […] “database.php” & “Thread.php” (Thread.php has been downloaded from here). database.php does some trivial tasks after connecting to a remote MondoDb database. Here’s […]

  70. Same PHP script is showing different output in browser than when it#39;s run from command lineCode and Programming

    […] “database.php” & “Thread.php” (Thread.php has been downloaded from here). database.php does some trivial tasks after connecting to a remote MondoDb database. Here’s […]

  71. Ricardo Fontanelli
    Ricardo Fontanelli at | | Reply

    Hi, thanks for sharing, when I used this class (by web browser), the response return ‘Content-type: text/html’ in my browser. Is it some Apache configuration?


    […] clase Thread NO la desarrollamos nosotros, el crédito es de Tudor, pero le hicimos unas modificaciones para que funcionara con clases, solo pasándole como parametro […]

  73. Catalin
    Catalin at | | Reply


    Nice job with fork, but i would like to know if creating a c++ extension for php and using c++ threads is not a better approach.
    As far as i know fork does not create genuine threads.


  74. ranaji
    ranaji at | | Reply

    i have an idea to use it on windows also you can leran it from below link.
    mutithreading in php .

  75. Is there a set time out equivalent in php? - PHP Solutions - Developers Q & A

    […] need to start new thread, try this http://blog.motane.lu/2009/01/02/multithreading-in-php/ This entry was posted in PHP on June 26, 2011 by […]

  76. Php multithreading (Php multihilos) | TusCodes

    […] clase Thread NO la desarrollamos nosotros, el crédito es de Tudor, pero le hicimos unas modificaciones para que funcionara con clases, solo pasándole como parametro […]

  77. a
    a at | | Reply

    i cant find threads.php file, can someone share asap?

  78. Mike
    Mike at | | Reply

    Just FYI.. The link to Thread.php is broken. I was able to copy it from a commentor but figured you might want to fix the link.


  79. a
    a at | | Reply

    can u upload a copy of it. so tht i can download, pls

  80. Dd
    Dd at | | Reply

    Cannot download! Clicking on the link redirects to a page with only plain text: “No input file specified.”

  81. soumik
    soumik at | | Reply

    thread.php not available in the following link ‘http://downloads.motane.lu/Thread.php’

  82. Manoj
    Manoj at | | Reply

    I tried to download ‘Thread.php’, but it’s giving me message in new page :- ‘No input file specified.’. Can anybody help?

  83. Vinayaka
    Vinayaka at | | Reply

    I am not able to downlod Threads class


  84. isbkch
    isbkch at | | Reply

    Link is dead, is there some chance you can fix it ?

  85. Jason
    Jason at | | Reply

    For some odd reason I have a legacy PHP script that uses this on PHP 5.2 without any problems but on PHP 5.5 the children that are forked hang and require a kill -9 to get rid of. Does this work on PHP 5.5 or do I need to look at the other script as the problem for the hang?

  86. Farhan ISlam
    Farhan ISlam at | | Reply

    Not sure if this helps or not, but I am looking for running a multithread application inside windows.

    Any alternative for windows based PHP program?

  87. Mu
    Mu at | | Reply

    Your test code above contains HTML errors,


    // start them
    $t1->start( 10, ‘t1’ );
    $t2->start( 10, ‘t2’ );

    is that supported to be:

    $t1 = start( 10, ‘t1’ );
    $t2 = start( 10, ‘t2’ );

    ITs all over the place

  88. Mu
    Mu at | | Reply

    ohh when I paste it here it fixed it self up.
    require_once( ‘Thread.php’ );

    // test to see if threading is available
    if( ! Thread::available() ) {
    die( ‘Threads not supported’ );

    // function to be ran on separate threads
    function paralel( $_limit, $_name ) {
    for ( $index = 0; $index < $_limit; $index++ ) {
    echo ‘Now running thread ‘ . $_name . PHP_EOL;
    sleep( 1 );

    // create 2 thread objects
    $t1 = new Thread( ‘paralel’ );
    $t2 = new Thread( ‘paralel’ );

    // start them
    $t1->start( 10, ‘t1’ );
    $t2->start( 10, ‘t2’ );

    // keep the program running until the threads finish
    while( $t1->isAlive() && $t2->isAlive() ) {

  89. Harpreet Bhatia
    Harpreet Bhatia at | | Reply

    First, thats a very nice code there. Really useful.
    Second, I am a bit concerned. I am on Ubuntu. while testing your code. i was also check current running processes using `htop.
    Now i found out that 2 new processes were created. but not killed.
    Why weren’t the processes killed? What should we do?

Leave a Reply

Advertisment ad adsense adlogger