• Pingback: Multithreading in php | PHP-Blog.com()

  • Raul

    Thanks! 😉

  • Did you try it on a live project? Can we see it at work? 😛

  • Raul

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

  • I’ve used it on a project, but it’s only available in intranet. But it works and that’s all that matters. If you have any suggestions of improvement, so share 😉

  • upsemshop

    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.
    Thx,
    upsemshop

  • 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. 🙂

  • 10x man, I’ll look into it and fix it later today. Sometime bugs escape one programmer just to be caught by another. That’s the beauty of Open Source.

  • I had a look at the code and it seems it was better the way it was. I made some tests, and, as if turned out, if I change that line and remove the $status variable, like such:

    it will yield an fatal error, saying:

    I always want to pass in 0 as an argument there, so there are two ways in which that can be achieved:

    Hope it’s clear for everybody now.

  • 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.

  • I’ve browsed the manual, as this entry is over one year old and I can’t remember why I took some decisions back then. It seems that you must always pass in a variable for the status to the function, in order to work. I’m not interested in the returned status, so I’ve passed in a zero variable.

  • George

    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

    http://www.php.net/manual/en/ref.pcntl.php#91224

    but it does not seem to work for me.

    Any ideas?

    Thanks,

    George

  • It won’t work like this. I think the best way to achieve multithreading is dropping PHP and switch to python or something else. Or rewrite in a different language the part you want to be multithreaded.

  • Zoli

    Hi,

    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

  • Good one, Zoli! I’ll update the Thread.php file in the future. Until then, you need to do the following: add “return” in front of the call_user_func_array() and
    call_user_func() calls so that the start() method will return the original function’s result. Like such:

    This is untested code, but it *should* work!

  • sims

    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.

  • Ricardo Sanchez

    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??

  • Ricardo Sanchez

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

    In class Thread:

    In function which uses Thread:

  • Shane Mc Cormack

    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.

  • Shane Mc Cormack

    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.

  • Encapsulate the value you want to pass on in an object. Since objects are always passed by reference in PHP, it should do the trick.

  • 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.

  • Try opening a permanent connection to the MySQL server!

  • Pingback: [PHP-mencoder] Des filigranes (watermark) dans vos flv avec PHP et mencoder « Emilien DAMART()

  • 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.

  • Mark

    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.

  • Tim

    Hi,

    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?

    Thanks,
    /Tim

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

  • Thanks for sharing this! Inspired by your work I published Threadi today.
    @see
    http://www.typo3-media.com/blog/multithreating-in-php.html
    https://github.com/danielpoe/Threadi

  • Thanks mate!

  • Make sure that the pnctl library is installed http://www.php.net/manual/en/book.pcntl.php . I think it’s in the repositories.

  • mr_mojtaba

    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?

  • mr_mojtaba

    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?
    Thanks

  • mr_mojtaba

    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

  • If it fails with that message, then the library is not installed. I just posted a link in the previous comment to the PHP manual’s section on the pnctl. Read it, install pnctl and it will work…

  • mr_mojtaba

    Thanks very much

  • mr_mojtaba

    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

  • Writing input to the db takes very little time and you really shouldn’t worry about that. This was only used in a CLI environment so I don’t know its exact behavior under Apache or whatever server you might be using.

  • Diego

    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…

  • Can you post some code?

  • Pingback: Marines MUD – W pogoni za RAMem()

  • Kailash

    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.

    Thanks,

  • 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).

    Cheers,

  • Dude…seriously!!! Do some reading…

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

  • Pingback: How To “Find And Replace” Words In Multiple Files In a Folder : Ranjith Siji – Programming the Web()

  • Pingback: Asynchrone Threads in PHP - php.de()

  • Jack

    Hello,
    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 ?

    Thanx

  • Pingback: O Senhor do PHP: A Irmandade dos Scripts | LordFokas.com – Blog()

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

    Regards,
    cojack.

  • Gdhami

    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,
    Gdhami.

  • Pingback: Linkdump #52: ABC PHP. « Tomasz Kowalczyk()

  • jost125

    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!

  • Bruno

    is there a sollution for windows system?

  • I don’t know! Might be, but I never use windows….

  • Pingback: Better Convert pdf to Multiple jpg | Dalibor Sojic()

  • Pingback: Netbeans Code Templates | The Playabl Blog()

  • sa

    is there a sollution for windows system?

  • Read the comment above yours…

  • Pingback: Why is realtime apps for php such a problem? - Quora()

  • 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

  • Suresh

    Hi,
    Thanks for your information

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

  • 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.

  • 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.

  • what just writing a plugin for sonic daemon?

  • victor wallin

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

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

  • I don’t think your code got pasted right. Use
    <pre lang=”php”>…</pre>
    to paste properly.

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

  • Very nice! Thanks for sharing.

  • Sanjoy

    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,
    Sanjay
    http://sanjoyinfoworld.blogspot.in

  • Sorry mate, I did not write Threadi, so I can’t offer support. You should contact the author, his name is Daniel Pötzinger and he blogs at http://www.typo3-media.com/blog/

    However, based on your error – class not found – you didn’t include the library correctly. But if you’re using a windows system, it won’t work as it relies on the pnctl_fork() function to spawn new “threads”. Just read the manual: http://www.php.net/manual/en/book.pcntl.php

    Good luck
    t.

  • Pingback: PHP multithreading through .NET interop « PHP / Zend / www.elcome!()

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

  • 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

    😉

  • Pingback: [PHP] Listener()

  • Pingback: Pointless Ramblings()

  • Damian

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

  • Lorin

    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.

  • Max

    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

  • Chey

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

    http://gearman.org/

  • Simon

    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?

  • Pingback: No Threading In Shared Servers « The Playabl Blog()

  • Pingback: Php script issue, syntax error | question code()

  • Gerben Wijnja

    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

  • Cheers mate! That was the coding standard of the company I was working for at the time. We weren’t using Zend’s coding standard!

  • redknight101

    How can I include max number of process?

  • 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??

  • 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. (:

  • Pingback: Same PHP script is showing different output in browser than when it’s run from command line()

  • Pingback: Same PHP script is showing different output in browser than when it#39;s run from command lineCode and Programming()

  • Ricardo Fontanelli

    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?

  • Pingback: PHP MULTITHREADING ( PHP MULTIHILOS ) | TusCodes.com()

  • Catalin

    Hi,

    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.

    Thx

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

  • Pingback: Is there a set time out equivalent in php? - PHP Solutions - Developers Q & A()

  • Pingback: Php multithreading (Php multihilos) | TusCodes()

  • a

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

  • 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.

    Cheers!

  • a

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

  • Dd

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

  • soumik

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

  • Manoj

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

  • Vinayaka

    I am not able to downlod Threads class

    http://downloads.motane.lu/Thread.php

  • isbkch

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

  • I have updated the link, it points to a github repository. Sorry about the inconvenience!

  • Jason

    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?

  • 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?

  • Tudor

    Sorry mate, I never use windows, so…

  • Mu

    Your test code above contains HTML errors,

    EG:

    // 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

  • Mu

    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() ) {
    sleep(1);
    }

  • Tudor

    Use pre tags to display code, as described on this page – http://tudorbarbu.ninja/the-blog/

  • Hi,
    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?

  • Siddiq

    i have tried your example script, but if i run the code, its only run once and just display once of my function, any idea to this case?

Advertisment ad adsense adlogger