所以我有一个主类调用另一个单例类,但是当运行多个线程(或并发线程)时,我会遇到交叉数据污染.这是一个非常简单的版本来解释这个问题.所有变量setter / getter都在Singleton中,由主类调用和设置.
class A {
public function doSomething($var) {
Singleton::instance()->setVar($var);
}
public function showSomething() {
return Singleton::instance()->getVar();
}
}
//单身人士
class Singleton {
private static $instance = null;
private $var;
public static function instance() {
if(!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
public function setVar($var) {
$this->var = $var;
}
public function getVar() {
return $this->var;
}
}
测试脚本1:
$actions = Array(
'one',
'two',
'three',
);
foreach($actions as $act) {
$action = new A();
$action->doSomething($act);
echo "Action: ".$action->showSomething()."
";
sleep(2);
}
测试脚本1输出将有;
one
two
three
测试脚本2:
$actions = Array(
'1',
'2',
'3',
);
foreach($actions as $act) {
$action = new A();
$action->doSomething($act);
echo "Action: ".$action->showSomething()."
";
sleep(2);
}
测试脚本2输出将有;
1
2
3
one
two
three
(不按此顺序,可能缺少其中一个值)
那么为什么在同时执行两个脚本时,测试2中包含测试1?
我是如何测试的:
打开两个终端,在每个终端执行一个脚本(因此睡眠),这样我就可以看到数据污染了.