개발! 딱 깔끔하고 센스있게!

PHP 애플리케이션에서 멀티 스레딩을 사용하는 방법 본문

개발 스크랩 메모/PHP

PHP 애플리케이션에서 멀티 스레딩을 사용하는 방법

렉사이 2020. 11. 21. 23:52

php 에서 다중 라인 모델을 실현하는 실제 방법이 있는지, 진실이든 아니면 모의일 뿐이다.

일정 기간 이전에 파일을 실행할 수 있는 다른 파일을 강제로 다운로드할 수 있는 다른 프로세스를 처리할 수 있도록 제안합니다.

이 문제는 php 코드가 실행될 때 php 실례가 메모리에 남아 있기 때문입니다.

그래서 당신이 몇 가지 시뮬레이션을 시뮬레이션한다면, 당신은 어떤 일이 발생할지 상상할 수 있습니다.

이 때문에 나는 여전히 php 에서 효과적으로 완성하거나 시뮬레이션을 할 수 있는 방법을 찾고 있다.

무슨 생각 있으세요?

대답

php 에서 다중 코일 을 사용할 수 있다

네, pthreads phreads로 다중 코드를 실행할 수 있습니다.

php 문서에서:

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.

Warning: The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.

단순 테스트

#!/usr/bin/php arg = $arg; } public function run() { if ($this->arg) { $sleep = mt_rand(1, 10); printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep); sleep($sleep); printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg); } } } // Create a array $stack = array(); //Initiate Multiple Thread foreach ( range("A", "D") as $i ) { $stack[] = new AsyncOperation($i); } // Start The Threads foreach ( $stack as $t ) { $t->start(); } ?> 

첫 운행

12:00:06pm: A -start -sleeps 5 12:00:06pm: B -start -sleeps 3 12:00:06pm: C -start -sleeps 10 12:00:06pm: D -start -sleeps 2 12:00:08pm: D -finish 12:00:09pm: B -finish 12:00:11pm: A -finish 12:00:16pm: C -finish 

제2차 운행

12:01:36pm: A -start -sleeps 6 12:01:36pm: B -start -sleeps 1 12:01:36pm: C -start -sleeps 2 12:01:36pm: D -start -sleeps 1 12:01:37pm: B -finish 12:01:37pm: D -finish 12:01:38pm: C -finish 12:01:42pm: A -finish 

현실 세계의 예

error_reporting(E_ALL); class AsyncWebRequest extends Thread { public $url; public $data; public function __construct($url) { $this->url = $url; } public function run() { if (($url = $this->url)) { /* * If a large amount of data is being requested, you might want to * fsockopen and read using usleep in between reads */ $this->data = file_get_contents($url); } else printf("Thread #%lu was not provided a URL\n", $this->getThreadId()); } } $t = microtime(true); $g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10)); /* starting synchronization */ if ($g->start()) { printf("Request took %f seconds to start ", microtime(true) - $t); while ( $g->isRunning() ) { echo "."; usleep(100); } if ($g->join()) { printf(" and %f seconds to finish receiving %d bytes\n", microtime(true) - $t, strlen($g->data)); } else printf(" and %f seconds to finish, request failed\n", microtime(true) - $t); } 
Comments