<p>Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes.</p>

<p>The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP.  So if you are simulating several threads you can imagine whats going to happen.  So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas?</p>

[{'answer_id': 71043, 'author': 'J.D. Fitz.Gerald', 'author_id': 11542, 'author_profile': 'https://Stackoverflow.com/users/11542', 'pm_score': 4, 'selected': False, 'text': '<p>While you can\'t thread, you do have some degree of process control in php. The two function sets that are useful here are:</p>\n\n<p>Process control functions\n<a href="http://www.php.net/manual/en/ref.pcntl.php" rel="noreferrer">http://www.php.net/manual/en/ref.pcntl.php</a></p>\n\n<p>POSIX functions\n<a href="http://www.php.net/manual/en/ref.posix.php" rel="noreferrer">http://www.php.net/manual/en/ref.posix.php</a></p>\n\n<p>You could fork your process with pcntl_fork - returning the PID of the child. Then you can use posix_kill to despose of that PID.</p>\n\n<p>That said, if you kill a parent process a signal should be sent to the child process telling it to die. If php itself isn\'t recognising this you could register a function to manage it and do a clean exit using pcntl_signal.</p>\n'}, {'answer_id': 72605, 'author': 'Adam Hopkinson', 'author_id': 12280, 'author_profile': 'https://Stackoverflow.com/users/12280', 'pm_score': 4, 'selected': False, 'text': '<p>You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won\'t wait for the command to finish.</p>\n\n<p>I can\'t quite remember the php CLI syntax, but you\'d want something like:</p>\n\n<pre><code>exec("/path/to/php -f \'/path/to/file.php\' | \'/path/to/output.txt\'");\n</code></pre>\n\n<p>I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.</p>\n'}, {'answer_id': 1079624, 'author': 'Ricardo', 'author_id': 132841, 'author_profile': 'https://Stackoverflow.com/users/132841', 'pm_score': 5, 'selected': False, 'text': '<p>Threading isn\'t available in stock PHP, but concurrent programming is possible by using HTTP requests as asynchronous calls.</p>\n\n<p>With the curl\'s timeout setting set to 1 and using the same session_id for the processes you want to be associated with each other, you can communicate with session variables as in my example below. With this method you can even close your browser and the concurrent process still exists on the server.</p>\n\n<p>Don\'t forget to verify the correct session ID like this:</p>\n\n<blockquote>\n  <p><a href="http://localhost/test/verifysession.php?sessionid=[the" rel="noreferrer">http://localhost/test/verifysession.php?sessionid=[the</a> correct id]</p>\n</blockquote>\n\n<h3>startprocess.php</h3>\n\n<pre><code>$request = "http://localhost/test/process1.php?sessionid=".$_REQUEST["PHPSESSID"];\n$ch = curl_init();\ncurl_setopt($ch, CURLOPT_URL, $request);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_TIMEOUT, 1);\ncurl_exec($ch);\ncurl_close($ch);\necho $_REQUEST["PHPSESSID"];\n</code></pre>\n\n<h3>process1.php</h3>\n\n<pre><code>set_time_limit(0);\n\nif ($_REQUEST["sessionid"])\n   session_id($_REQUEST["sessionid"]);\n\nfunction checkclose()\n{\n   global $_SESSION;\n   if ($_SESSION["closesession"])\n   {\n       unset($_SESSION["closesession"]);\n       die();\n   }\n}\n\nwhile(!$close)\n{\n   session_start();\n   $_SESSION["test"] = rand();\n   checkclose();\n   session_write_close();\n   sleep(5);\n}\n</code></pre>\n\n<h3>verifysession.php</h3>\n\n<pre><code>if ($_REQUEST["sessionid"])\n    session_id($_REQUEST["sessionid"]);\n\nsession_start();\nvar_dump($_SESSION);\n</code></pre>\n\n<h3>closeprocess.php</h3>\n\n<pre><code>if ($_REQUEST["sessionid"])\n    session_id($_REQUEST["sessionid"]);\n\nsession_start();\n$_SESSION["closesession"] = true;\nvar_dump($_SESSION);\n</code></pre>\n'}, {'answer_id': 3579723, 'author': 'Pete', 'author_id': 432373, 'author_profile': 'https://Stackoverflow.com/users/432373', 'pm_score': 3, 'selected': False, 'text': "<p>You could simulate threading.  PHP can run background processes via popen (or proc_open).  Those processes can be communicated with via stdin and stdout.  Of course those processes can themselves be a php program.  That is probably as close as you'll get.  </p>\n"}, {'answer_id': 4350418, 'author': 'masterb', 'author_id': 529958, 'author_profile': 'https://Stackoverflow.com/users/529958', 'pm_score': 6, 'selected': False, 'text': '<p>why don\'t you use <a href="https://secure.php.net/manual/en/function.popen.php" rel="noreferrer">popen</a>?</p>\n<pre><code>for ($i=0; $i&lt;10; $i++) {\n    // open ten processes\n    for ($j = 0; $j &lt; 10; $j++) {\n        $pipe[$j] = popen(\'script2.php\', \'w\');\n    }\n\n    // wait for them to finish\n    for ($j = 0; $j &lt; 10; ++$j) {\n        pclose($pipe[$j]);\n    }\n}\n</code></pre>\n'}, {'answer_id': 4790074, 'author': 'Sheldmandu', 'author_id': 2641644, 'author_profile': 'https://Stackoverflow.com/users/2641644', 'pm_score': 3, 'selected': False, 'text': "<p>Depending on what you're trying to do you could also use curl_multi to achieve it.</p>\n"}, {'answer_id': 5946750, 'author': 'Manoj Donga', 'author_id': 746369, 'author_profile': 'https://Stackoverflow.com/users/746369', 'pm_score': 3, 'selected': False, 'text': '<p>You can have option of:</p>\n\n<ol>\n<li>multi_curl</li>\n<li>One can use system command for the same</li>\n<li>Ideal scenario is, create a threading function in C language and compile/configure in PHP. Now that function will be the function of PHP.</li>\n</ol>\n'}, {'answer_id': 8844548, 'author': 'Jarrod', 'author_id': 577306, 'author_profile': 'https://Stackoverflow.com/users/577306', 'pm_score': 3, 'selected': False, 'text': '<p>How about pcntl_fork?</p>\n\n<p>check our the manual page for examples: <a href="http://php.net/manual/en/function.pcntl-fork.php" rel="nofollow noreferrer">PHP pcntl_fork</a></p>\n\n<pre><code>&lt;?php\n\n    $pid = pcntl_fork();\n    if ($pid == -1) {\n        die(\'could not fork\');\n    } else if ($pid) {\n        // we are the parent\n        pcntl_wait($status); //Protect against Zombie children\n    } else {\n        // we are the child\n    }\n\n?&gt;\n</code></pre>\n'}, {'answer_id': 9107047, 'author': 'Stilero', 'author_id': 1180559, 'author_profile': 'https://Stackoverflow.com/users/1180559', 'pm_score': 2, 'selected': False, 'text': "<p><code>pcntl_fork</code> won't work in a web server environment if it has <em>safe mode</em> turned on. In this case, it will only work in the CLI version of PHP.</p>\n"}, {'answer_id': 12487840, 'author': 'JasonDavis', 'author_id': 143030, 'author_profile': 'https://Stackoverflow.com/users/143030', 'pm_score': 4, 'selected': False, 'text': '<p>I know this is an old question but for people searching, there is a PECL extension written in C that gives PHP multi-threading capability now, it\'s located here <a href="https://github.com/krakjoe/pthreads" rel="noreferrer">https://github.com/krakjoe/pthreads</a></p>\n'}, {'answer_id': 15501449, 'author': 'Baba', 'author_id': 1226894, 'author_profile': 'https://Stackoverflow.com/users/1226894', 'pm_score': 9, 'selected': False, 'text': '<h1>Multi-threading is possible in php</h1>\n\n<p>Yes you can do multi-threading in PHP with <a href="https://github.com/krakjoe/pthreads" rel="noreferrer">pthreads</a> </p>\n\n<p>From <a href="http://www.php.net/manual/en/intro.pthreads.php" rel="noreferrer">the PHP documentation</a>:</p>\n\n<blockquote>\n  <p>pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.</p>\n  \n  <p><strong>Warning</strong>:\n  The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.</p>\n</blockquote>\n\n<p><strong>Simple Test</strong></p>\n\n<pre><code>#!/usr/bin/php\n&lt;?php\nclass AsyncOperation extends Thread {\n\n    public function __construct($arg) {\n        $this-&gt;arg = $arg;\n    }\n\n    public function run() {\n        if ($this-&gt;arg) {\n            $sleep = mt_rand(1, 10);\n            printf(\'%s: %s  -start -sleeps %d\' . "\\n", date("g:i:sa"), $this-&gt;arg, $sleep);\n            sleep($sleep);\n            printf(\'%s: %s  -finish\' . "\\n", date("g:i:sa"), $this-&gt;arg);\n        }\n    }\n}\n\n// Create a array\n$stack = array();\n\n//Initiate Multiple Thread\nforeach ( range("A", "D") as $i ) {\n    $stack[] = new AsyncOperation($i);\n}\n\n// Start The Threads\nforeach ( $stack as $t ) {\n    $t-&gt;start();\n}\n\n?&gt;\n</code></pre>\n\n<p>First Run</p>\n\n<pre><code>12:00:06pm:     A  -start -sleeps 5\n12:00:06pm:     B  -start -sleeps 3\n12:00:06pm:     C  -start -sleeps 10\n12:00:06pm:     D  -start -sleeps 2\n12:00:08pm:     D  -finish\n12:00:09pm:     B  -finish\n12:00:11pm:     A  -finish\n12:00:16pm:     C  -finish\n</code></pre>\n\n<p>Second Run </p>\n\n<pre><code>12:01:36pm:     A  -start -sleeps 6\n12:01:36pm:     B  -start -sleeps 1\n12:01:36pm:     C  -start -sleeps 2\n12:01:36pm:     D  -start -sleeps 1\n12:01:37pm:     B  -finish\n12:01:37pm:     D  -finish\n12:01:38pm:     C  -finish\n12:01:42pm:     A  -finish\n</code></pre>\n\n<p><strong>Real World Example</strong></p>\n\n<pre><code>error_reporting(E_ALL);\nclass AsyncWebRequest extends Thread {\n    public $url;\n    public $data;\n\n    public function __construct($url) {\n        $this-&gt;url = $url;\n    }\n\n    public function run() {\n        if (($url = $this-&gt;url)) {\n            /*\n             * If a large amount of data is being requested, you might want to\n             * fsockopen and read using usleep in between reads\n             */\n            $this-&gt;data = file_get_contents($url);\n        } else\n            printf("Thread #%lu was not provided a URL\\n", $this-&gt;getThreadId());\n    }\n}\n\n$t = microtime(true);\n$g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10));\n/* starting synchronization */\nif ($g-&gt;start()) {\n    printf("Request took %f seconds to start ", microtime(true) - $t);\n    while ( $g-&gt;isRunning() ) {\n        echo ".";\n        usleep(100);\n    }\n    if ($g-&gt;join()) {\n        printf(" and %f seconds to finish receiving %d bytes\\n", microtime(true) - $t, strlen($g-&gt;data));\n    } else\n        printf(" and %f seconds to finish, request failed\\n", microtime(true) - $t);\n}\n</code></pre>\n'}, {'answer_id': 19713701, 'author': 'pinkal vansia', 'author_id': 1606631, 'author_profile': 'https://Stackoverflow.com/users/1606631', 'pm_score': 4, 'selected': False, 'text': '<p>using threads is made possible by the pthreads PECL extension</p>\n\n<p><a href="http://www.php.net/manual/en/book.pthreads.php">http://www.php.net/manual/en/book.pthreads.php</a></p>\n'}, {'answer_id': 19789433, 'author': 'Pir Abdul', 'author_id': 665485, 'author_profile': 'https://Stackoverflow.com/users/665485', 'pm_score': -1, 'selected': False, 'text': '<p>Multithreading means performing multiple tasks or processes simultaneously, we can achieve this in php by using following code,although there is no direct way to achieve multithreading in php but we can achieve almost same results by following way.</p>\n\n<pre><code>chdir(dirname(__FILE__));  //if you want to run this file as cron job\n for ($i = 0; $i &lt; 2; $i += 1){\n exec("php test_1.php $i &gt; test.txt &amp;");\n //this will execute test_1.php and will leave this process executing in the background and will go         \n\n //to next iteration of the loop immediately without waiting the completion of the script in the   \n\n //test_1.php , $i  is passed as argument .\n</code></pre>\n\n<p>}</p>\n\n<p>Test_1.php</p>\n\n<pre><code>$conn=mysql_connect($host,$user,$pass);\n$db=mysql_select_db($db);\n$i = $argv[1];  //this is the argument passed from index.php file\nfor($j = 0;$j&lt;5000; $j ++)\n{\nmysql_query("insert  into  test   set\n\n                id=\'$i\',\n\n                comment=\'test\',\n\n                datetime=NOW() ");\n\n}\n</code></pre>\n\n<p>This will execute test_1.php two times simultaneously and both process will run in the background simultaneously ,so in this way you can achieve multithreading in php.</p>\n\n<p>This guy done really good work  <a href="https://github.com/krakjoe/pthreads" rel="nofollow">Multithreading in php</a></p>\n'}, {'answer_id': 52125027, 'author': 'Martin Vahi', 'author_id': 855783, 'author_profile': 'https://Stackoverflow.com/users/855783', 'pm_score': -1, 'selected': False, 'text': '<p>As of the writing of my current comment, I don\'t know about the PHP threads. I came to look for the answer here myself, but one workaround is that the PHP program that receives the request from the web server delegates the whole answer formulation to a console application that stores its output, the answer to the request, to a binary file and the PHP program that launched the console application returns that binary file byte-by-byte as the answer to the received request. The console application can be written in any programming language that runs on the server, including those that have proper threading support, including C++ programs that use OpenMP.</p>\n\n<p>One unreliable, dirty, trick is to use PHP for executing a console application, "uname",</p>\n\n<pre><code>uname -a\n</code></pre>\n\n<p>and print the output of that console command to the HTML output to find out the exact version of the server software. Then install the exact same version of the software to a VirtualBox instance, compile/assemble whatever fully self-contained, preferably static, binaries that one wants and then upload those to the server. From that point onwards the PHP application can use those binaries in the role of the console application that has proper multi-threading. It\'s a dirty, unreliable, workaround to a situation, when the server administrator has not installed all needed programming language implementations to the server. The thing to watch out for is that at every request that the PHP application receives the console application(s) terminates/exit/get_killed. </p>\n\n<p>As to what the hosting service administrators think of such server usage patterns, I guess it boils down to culture. In Northern Europe the service provider HAS TO DELIVER WHAT WAS ADVERTISED and if execution of console commands was allowed and uploading of non-malware files was allowed and the service provider has a right to kill any server process after a few minutes or even after 30 seconds, then the hosting service administrators lack any arguments for forming a proper complaint. In United States and Western Europe the situation/culture is very different and I believe that there\'s a great chance that in U.S. and/or Western Europe the hosting service provider will \n refuse to serve hosting service clients that use the above described trick. That\'s just my guess, given my personal experience with U.S. hosting services and given what I have heard from others about Western European hosting services. As of the writing of my current comment(2018_09_01) I do not know anything about the cultural norms of the Southern-European hosting service providers, Southern-European network administrators.</p>\n'}, {'answer_id': 61505176, 'author': 'Юрий Ярвинен', 'author_id': 10738019, 'author_profile': 'https://Stackoverflow.com/users/10738019', 'pm_score': 3, 'selected': False, 'text': '<p>If you are using a Linux server, you can use </p>\n\n<pre><code>exec("nohup $php_path path/script.php &gt; /dev/null 2&gt;/dev/null &amp;")\n</code></pre>\n\n<p>If you need pass some args </p>\n\n<pre><code>exec("nohup $php_path path/script.php $args &gt; /dev/null 2&gt;/dev/null &amp;")\n</code></pre>\n\n<p>In script.php</p>\n\n<pre><code>$args = $argv[1];\n</code></pre>\n\n<p>Or use Symfony\n<a href="https://symfony.com/doc/current/components/process.html" rel="noreferrer">https://symfony.com/doc/current/components/process.html</a></p>\n\n<pre><code>$process = Process::fromShellCommandline("php ".base_path(\'script.php\'));\n$process-&gt;setTimeout(0);     \n$process-&gt;disableOutput();     \n$process-&gt;start();\n</code></pre>\n'}, {'answer_id': 71617864, 'author': 'Justin Jack', 'author_id': 1678210, 'author_profile': 'https://Stackoverflow.com/users/1678210', 'pm_score': 2, 'selected': False, 'text': '<p>I know this is an old question, but this will undoubtedly be useful to many: <a href="https://github.com/justincjack/phpthreads" rel="nofollow noreferrer">PHPThreads</a></p>\n<p>Code Example:</p>\n<pre><code>function threadproc($thread, $param) {\n \n    echo &quot;\\tI\'m a PHPThread.  In this example, I was given only one parameter: \\&quot;&quot;. print_r($param, true) .&quot;\\&quot; to work with, but I can accept as many as you\'d like!\\n&quot;;\n \n    for ($i = 0; $i &lt; 10; $i++) {\n        usleep(1000000);\n        echo &quot;\\tPHPThread working, very busy...\\n&quot;;\n    }\n \n    return &quot;I\'m a return value!&quot;;\n}\n \n\n$thread_id = phpthread_create($thread, array(), &quot;threadproc&quot;, null, array(&quot;123456&quot;));\n \necho &quot;I\'m the main thread doing very important work!\\n&quot;;\n \nfor ($n = 0; $n &lt; 5; $n++) {\n    usleep(1000000);\n    echo &quot;Main thread...working!\\n&quot;;\n}\n \necho &quot;\\nMain thread done working.  Waiting on our PHPThread...\\n&quot;;\n \nphpthread_join($thread_id, $retval);\n \necho &quot;\\n\\nOur PHPThread returned: &quot; . print_r($retval, true) . &quot;!\\n&quot;;\n</code></pre>\n<p>Requires PHP extensions:</p>\n<ul>\n<li>posix</li>\n<li>pcntl</li>\n<li>sockets</li>\n</ul>\n<p>I\'ve been using this library in production now for months.  I put a LOT of effort into making it feel like using POSIX pthreads.  If you\'re comfortable with pthreads, you can pick this up and use it very effectively in no time.</p>\n<p>Computationally, the inner workings are quite different, but practically, the functionality is nearly the same including semantics and syntax.</p>\n<p>I\'ve used it to write an extremely efficient WebSocket server that supports high throughput rates. Sorry, I\'m rambling.  I\'m just excited that I finally got it released and I want to see who it will help!</p>\n'}, {'answer_id': 74086559, 'author': 'gzhegow', 'author_id': 2119205, 'author_profile': 'https://Stackoverflow.com/users/2119205', 'pm_score': 0, 'selected': False, 'text': '<p>popen()/proc_open() works parallel even in Windows.</p>\n<p>Most often pitfall is &quot;fread/stream_get_contents&quot; without while loop. Once you try to fread() from running process it will block output for processes that run after it (cause of fread() waits until at least one byte arrives)</p>\n<p>Add stream_select(). Closest analogy is &quot;foreach with timeout but for streams&quot;, you pass few arrays to read and write and each call of stream_select() one or more streams will be selected. Function updates original arrays by reference, so dont forget to restore it to all streams before next call. Function gives them some time to read or write. If no content - control returns allowing us to retry cycle.</p>\n<pre class="lang-php prettyprint-override"><code>// sleep.php\nset_error_handler(function ($severity, $error, $file, $line) {\n    throw new ErrorException($error, -1, $severity, $file, $line);\n});\n\n$sleep = $argv[ 1 ];\n\nsleep($sleep);\n\necho $sleep . PHP_EOL;\n\nexit(0);\n</code></pre>\n<pre class="lang-php prettyprint-override"><code>// run.php\n&lt;?php\n\n$procs = [];\n$pipes = [];\n\n$cmd = \'php %cd%/sleep.php\';\n\n$desc = [\n    0 =&gt; [ \'pipe\', \'r\' ],\n    1 =&gt; [ \'pipe\', \'w\' ],\n    2 =&gt; [ \'pipe\', \'a\' ],\n];\n\nfor ( $i = 0; $i &lt; 10; $i++ ) {\n    $iCmd = $cmd . \' \' . ( 10 - $i ); // add SLEEP argument to each command 10, 9, ... etc.\n\n    $proc = proc_open($iCmd, $desc, $pipes[ $i ], __DIR__);\n\n    $procs[ $i ] = $proc;\n}\n\n$stdins = array_column($pipes, 0);\n$stdouts = array_column($pipes, 1);\n$stderrs = array_column($pipes, 2);\n\nwhile ( $procs ) {\n    foreach ( $procs as $i =&gt; $proc ) {\n        // @gzhegow &gt; [OR] you can output while script is running (if child never finishes)\n        $read = [ $stdins[ $i ] ];\n        $write = [ $stdouts[ $i ], $stderrs[ $i ] ];\n        $except = [];\n        if (stream_select($read, $write, $except, $seconds = 0, $microseconds = 1000)) {\n            foreach ( $write as $stream ) {\n                echo stream_get_contents($stream);\n            }\n        }\n\n        $status = proc_get_status($proc);\n\n        if (false === $status[ \'running\' ]) {\n            $status = proc_close($proc);\n            unset($procs[ $i ]);\n\n            echo \'STATUS: \' . $status . PHP_EOL;\n        }\n\n        // @gzhegow &gt; [OR] you can output once command finishes\n        // $status = proc_get_status($proc);\n        //\n        // if (false === $status[ \'running\' ]) {\n        //     if ($content = stream_get_contents($stderrs[ $i ])) {\n        //         echo \'[ERROR]\' . $content . PHP_EOL;\n        //     }\n        //\n        //     echo stream_get_contents($stdouts[ $i ]) . PHP_EOL;\n        //\n        //     $status = proc_close($proc);\n        //     unset($procs[ $i ]);\n        //\n        //     echo \'STATUS: \' . $status . PHP_EOL;\n        // }\n    }\n\n    usleep(1); // give your computer one tick to decide what thread should be used\n}\n\n// ensure you receive 1,2,3... but you\'ve just run it 10,9,8...\n\nexit(0);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/70855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11190/']