如何使用pthread访问数组变量,我创建了一个线程类名“AccessVariable”,谁的任务是创建4个线程并访问名为“$ arr”的数组< / strong>,需要一些关于如何解决这个问题的指针,因为我在这个编码中是非常新的
<?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();
}
?>
答案 0 :(得分:2)
您会发现一些有用的观察结果:
-
<?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上有很多例子,并且包含在发行版中,以帮助您更好地了解pthreads以便使用它。多线程与使用新数据库或http客户端不同。它复杂而有力,我恳请您仔细阅读并充分阅读所有示例,即使您认为它与手头的任务无关;知识将为你服务。
除了示例之外,github上过去的bug报告还有很多信息,所以如果你遇到问题并且在一个例子中似乎没有解决方案,那么在报告任何错误之前搜索github上的问题列表。