【发布时间】:2022-12-28 10:36:50
【问题描述】:
问题
我写了代码的多线程实现,并尝试使用redis作为计数器,这是我的代码。当我尝试将redis用作计数器时,我经常在值中得到':'(冒号),有时却没有,是因为我循环太快而redis甚至没有注意到吗?
输出结果
cclilshy@192 debug % php st.php
registerRedis success!
registerSocket success!
1
2
3
1
2
string(2) ":5"
1
2
3
string(2) ":9"
3
string(1) "9"
// the up is the output. Why?
代码
$func = function($handle){
for($i=0;$i<3;$i++){
echo $handle->counter().PHP_EOL;
}
var_dump($handle->total());
};
//$handle->counter() :
public function counter($record = true){
if($record = false){
return $this->count;
}
$this->thread->counter();
$this->count++;
return $this->count;
}
//$handle->total() :
public function total(){
return $this->thread->counter(false);
}
//$handle->thread->counter() :
public function counter($record = true){
if($record === false){
return $this->redis->get('thread.' . $this->pids[0] . '.count');
}
return $this->redis->incr('thread.' . $this->pids[0] . '.count');
}
【问题讨论】: