我对以下简化代码的结果感到困惑。
线程对象MyPool将实例化可变数量的MyWorker对象。当正确地实例化每个MyWorker对象时,它应在MyPool类中增加$ counter,以反映有多少个正确实例化的工作程序。
当从MyWorker对象内部调用时,递增计数函数()函数似乎已执行(根据echo语句),但对$ counter属性没有影响。但是,从主线程调用相同的代码可以正常工作。
如何实现这个简单的概念?
<?php
error_reporting(E_ALL & ~E_NOTICE);
class MyPool extends Threaded
{
public static $counter;
public $workers;
public function __construct()
{
self::$counter = (int) 0;
$workers[] = new MyWorker();
$workers[] = new MyWorker();
$workers[] = new MyWorker();
$workers[0]->start();
$workers[1]->start();
$workers[2]->start();
}
public static function getCounter()
{
return self::$counter;
}
public static function increaseCounter()
{
self::$counter++;
echo "counter has been increased inside MyPool\n";
}
}
class MyWorker extends Worker
{
public function __construct()
{
}
public function run()
{
// do something then
$this->WorkerActive();
}
public function WorkerActive()
{
MyPool::$counter++;
MyPool::increaseCounter();
}
}
$MyPool = new MyPool();
echo "counter = ".MyPool::$counter."\n";
echo "counter = ".$MyPool->getCounter()."\n";
echo "counter = ".MyPool::getCounter()."\n";
MyPool::$counter++;
MyPool::increaseCounter();
echo "counter = ".MyPool::$counter."\n";
echo "counter = ".$MyPool->getCounter()."\n";
echo "counter = ".MyPool::getCounter()."\n";
输出为:
counter has been increased inside MyPool
counter has been increased inside MyPool
counter has been increased inside MyPool
counter = 0
counter = 0
counter = 0
counter has been increased inside MyPool
counter = 2
counter = 2
counter = 2
答案 0 :(得分:0)
在pthreads中,静态属性是线程局部的,并且不在线程之间共享。将$ counter属性切换到对象范围会有所帮助。