skip to Main Content

The problem

I wrote a multi-threaded implementation of the code and tried to use redis as a counter, this is my code. When I try to use redis as a counter, I often get ‘:'(colon) in the value, sometimes not, is it because I loop too fast and redis doesn’t even notice?

Output result

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?

Code


$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');
}

2

Answers


  1. Chosen as BEST ANSWER

    I solved this problem by using a separate redis connection for each process


  2. Redis is single-threaded by design, so it’s anyway serves your threads in sync way.

    Response looks like this because RESP protocol are not parsed and it returns you raw representation for integer.

    Yeah, one of the reason could be that parser process is still blocked at the time you’re already returns next value

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search