개발 스크랩 메모/PHP
php 에서 비동기 함수 실행
렉사이
2020. 12. 13. 22:39
일부 비동기 운행 기능 을 가 진 pp 클래스 를 만 들 수 있 습 니까?다음은 내 가 지금까지 한 일이 다.
class Worker extends Thread { protected $asyncFun; protected $paramsArray; public function run() { $asyncFun(/*parameters go here*/) } public function setAsyncFunction($func, $paramsArr) { $this->asyncFun = $func; $this->paramsArray = $paramsArr; } }
나 는 그것 을 이렇게 부 르 고 싶다.
$worker = new Worker(); $worker->setAsyncFunction(foo, ["a", "b"]); $worker::start();
대답 하 다.
최신 버 전의 Pthreads 는 패 킷 을 구성원 으로 지원 합 니 다.
이 때문에 코드 는 매우 간단 합 니 다.
call = $call; $this->args = $args; } public function run() { call_user_func_array($this->call, $this->args); } protected $call; protected $args; } $background = new Background(function($greeting){ printf("%s\n", $greeting); }, ["Hello World"]); $background->start(); $background->join(); function named($greeting) { printf("%s\n", $greeting); } $background = new Background("named", ["Goodbye World"]); $background->start(); $background->join(); ?>
그러나 이 는 무 서운 것 이다.
함수 가 이렇게 갈증 이 나 서 자신의 동선 이 필요 하 다 는 것 은 상상 하기 어렵다.
올 바른 경로 로 시 작 했 습 니 다.
컨 텍스트 를 다시 사용 하고 작업 스 레 드 를 만들어 야 한다 고 생각 합 니 다.
pthreads 에 모든 것 이 내장 되 어 있 습 니 다.
더 합 리 적 인 코드 는 내장 류 를 사용 하면 더욱 비슷 해 보 입 니 다:
call = $call; $this->args = $args; } public function run() { call_user_func_array($this->call, $this->args); } protected $call; protected $args; } $pool = new Pool(4); $pool->submit(new Background(function($greeting){ printf("%s\n", $greeting); }, ["Hello World"])); $pool->shutdown(); ?>
하지만 반환 치 는 언급 되 지 않 았 다.
저 는 귀하 가 사용 하 는 풀 을 검색 해서 호출 하 는 결 과 를 가정 합 니 다.
이런 상황 에서 코드 가 더욱 비슷 해 보 입 니 다.
call = $call; $this->args = $args; } public function run() { $this->synchronized(function(){ $this->result = call_user_func_array ($this->call, $this->args); $this->notify(); }); } public function getResult() { return $this->synchronized(function(){ while (!isset($this->result)) $this->wait(); return $this->result; }); } protected $call; protected $args; protected $result; } $pool = new Pool(4); $call = new Background(function($greeting){ return sprintf("%s\n", $greeting); }, ["Hello World"]); $pool->submit($call); echo $call->getResult(); $pool->shutdown(); ?>
보다 시 피 Background: getResult 의 호출 은 문맥 을 통 해 컨 텍스트 를 사용 할 수 있 습 니 다.
이것 은 취 할 수도 있 고 취 할 수도 없 지만 좋 은 예 입 니 다.