簡體   English   中英

使用pthreads在PHP中創建異步超時

[英]Using pthreads to create an asynchronous timeout in PHP

我正在嘗試在PHP中創建某種異步超時。

我正在使用PECL擴展pthreads來實現多線程。

異步超時可以完美地工作,但是引用卻不能。

我正在使用PHP 5.5.8進行此測試。

class ParentClass {
    public $test;

    public function __construct(){
    }

    public function test() {
        echo $this->test;
    }
}

class Timeout extends Thread {
    private $seconds;
    private $parent;

    public function __construct($seconds, &$parent){
        $this->seconds = $seconds;
        $this->parent = $parent;
    }

    public function run(){
        sleep($this->seconds);
        $this->parent->test();
    }
}

$parent = new ParentClass();
$parent->test = "Hello.\n";
$timeout = new Timeout(2, $parent);
$timeout->start();
$parent->test = "Bye.\n";
$parent->test();

期待

Bye.
Bye.

入門

Bye.
Hello.

有人能告訴我我做錯了什么嗎?

您不應該將sleep()用於多線程應用程序,PHP調用的底層實現旨在使進程進入休眠狀態,而不是進程中的線程。 里程會有所不同,某些實現可能會導致線程休眠,但您不能也不應該依賴它。

usleep更適合多線程,因為它旨在使線程進入睡眠狀態,而不是進程進入睡眠狀態,但是,它也使線程處於非接受狀態。

pthreads內置了為多線程設計的正確同步方法,這些同步方法在等待某些事件發生時將線程保持在接受狀態。

如果您希望在多個上下文之間傳遞一個對象進行操作,則引用不起作用,也不必執行,該對象應該從pthreads下降。

<?php
define("SECOND", 1000000);

class ParentClass extends Stackable {

    public function test() {
        echo $this->test;
    }

    public function run(){}

    public $test;
}

class Timeout extends Thread {

    public function __construct($seconds, $parent){
        $this->seconds = $seconds;
        $this->parent = $parent;
    }

    public function run(){
        $this->synchronized(function(){
            $this->wait(
                SECOND * $this->seconds);
        });
        $this->parent->test();
    }

    private $seconds;
    private $parent;
}

$parent = new ParentClass();
$parent->test = "Hello.\n";
$timeout = new Timeout(2, $parent);
$timeout->start();
$parent->test = "Bye.\n";
$parent->test();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM