Search code examples
phpmultithreadingcompilationpthreadsphalanger

How do you get pthreads to compile with Phalanger?


So i have pthreads working with PHP on windows, but how can i compile and run my pthreads implementations with phalanger 3.0? At the moment, it builds with 0 errors / 0 warnings, but then when i run it it says

CompileError: The class 'ThreadTest' is incomplete - its base class or interface is unknown in C:\phptests\thread.php on line 10, column 1.

I see in the Phalanger install dir it has the php extensions .dll's; and the php_pthreads zip i downloaded it has .pdb intermediate files for the pthreads .dll's, so is there a way to get Phalanger to compile and run pthreads?


Solution

  • Phalanger does not have a support for pthreads.

    You can use .NET alternatives via clr_create_thread(callback [, parameters]) function or sb. has to implement missing support for pthreads in C#.

    clr_create_thread is bit misleading name though, as it doesn't really create a thread. Instead it takes your callback and schedules it for execution on a ThreadPool. Threads on a thread pool are somewhat special as they do not end when your callback ends. Instead they are reused for later requests (like if you call clr_create_thread again the callback execution may end up on the thread you used previously). As such, there's little sense in Joining ThreadPool threads, as they do not end voluntarily. However, you may use other .net synchronization mechanisms if you want to wait for your callback(s) to finish (AutoResetEvent and WaitHandle::WaitAll are the important parts):

    use System\Threading;
    class ThreadTest
    {
        public static function main()
        {
            (new self)->run();
        }
    
        public function run()
        {
            $that = $this;
    
            $finished = [];
    
            for ($i = 0; $i < 5; $i++) {
                $finished[$i] = new Threading\AutoResetEvent(false);
                clr_create_thread(function() use ($that, $finished, $i) {
                    $that->inathread();
                    $finished[$i]->Set();
                });
            }
    
            Threading\WaitHandle::WaitAll($finished);
            echo "Main ended\n";
        }
    
        public function inathread()
        {
            $limit = rand(0, 15);
            $threadId = Threading\Thread::$CurrentThread->ManagedThreadId->ToString();
            echo "\n thread $threadId limit: " . $limit . " \n";
            for ($i = 0; $i < $limit; $i++) {
                echo "\n thread " . $threadId . " executing \n";
                Threading\Thread::Sleep(1000);
            }
            echo "\n thread $threadId ended \n";
        }
    }