1

如何使用 pthread 访问数组变量,我创建了一个线程类名称“AccessVariable”,其任务是创建 4 个线程并访问名为“$arr”的数组,需要一些关于如何实现这一点的指针,因为我非常此编码中的新内容

<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
class AccessVariable extends Thread {
    public $arr = array("12","33","21","3211","3214","34","23423");  
    public function __construct($arg) {
        $this->arg = $arg;
    }
    public function run() {
        if ($this->arg) {
            $tmp_value = $this->getValue();
            printf('%s: %s %d -finish' . "\n", date("g:i:sa"), $this->arg, $tmp_value);
        }
        $this->synchronized(function($thread) {
                    $thread->getValue();
                }, $this);
    }
    public function getValue() {
        //Get Array Variable
    }
}
// Create a array
$stack = array();
//Iniciate Miltiple Thread
foreach (range("A", "D") as $i) {
    $stack[] = new AccessVariable($i);
}
// Start The Threads
foreach ($stack as $t) {
    $t->start();
}
?>
4

1 回答 1

2

您会发现一些有用的观察结果:

  • 不支持类条目默认值 - zend 有对象处理程序但没有条目处理程序,当声明一个条目时,对象处理程序显然不适合调用,因为它们与实例一起工作。要解决此问题,请在构造函数中设置默认值。
  • 用于在多个上下文之间共享的变量应该扩展 pthreads 定义;pthreads 对象作为对象起作用,并且关联数组和索引列表,这些东西的默认 PHP 实现没有为多线程做好准备。
  • 仅当您打算在同步块中使用同步方法(php 中的闭包/函数)时,对对象进行同步才有用;仅在您打算等待或通知其他等待和反对时才同步

-

<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);

class SharedArray extends Stackable {
    public function __construct($array) {
        $this->merge($array);
    }

    public function run(){}
}


class AccessSharedArray extends Thread {
    public $shared;
    public $arg;

    public function __construct($shared, $arg) {
        $this->shared = $shared;
        $this->arg = $arg;
    }

    public function run() {
        if ($this->arg) {
            $tmp_value = $this->shared[$this->arg];
            printf('%s: %s %d -finish' . "\n", date("g:i:sa"), $this->arg, $tmp_value);
        }
    }
}

$shared = new SharedArray(
    array("12","33","21","3211","3214","34","23423"));
// Create a array
$stack = array();

foreach (range(0, 3) as $i) {
    $stack[] = new AccessSharedArray($shared, $i);
}

// Start The Threads
foreach ($stack as $t) {
    $t->start();
}

foreach ($stack as $t)
    $t->join();
?>

github 上有很多示例,并包含在分发版中,以帮助您充分了解 pthread 以使用它。多线程不像使用新的数据库或 http 客户端。它复杂而强大,我恳请您仔细阅读所有包含的示例,即使您认为它与手头的任务无关;不管怎样,知识都会很好地为你服务。

除了示例之外,github 上过去的错误报告中还有很多信息,因此如果您遇到问题并且示例中似乎没有解决方案,请在报告任何错误之前搜索 github 上的问题列表。

于 2013-06-19T05:42:07.037 回答