pthreads如何销毁完成的套接字连接

时间:2016-11-04 20:09:31

标签: php multithreading sockets pthreads

我的代码如下,使用php7-zts和pthreads。我想知道如何正确清理已完成的客户端,以免造成内存泄漏。

<?php

class Client extends Thread {        
    public function __construct($socket){
        $this->socket = $socket;
        $this->start();
    }
    public function run(){                
        $msgsock = $this->socket;
        if ($msgsock) { 
            if (false === ($buf = socket_read($msgsock, 2048, PHP_BINARY_READ))) {
                echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            }

            ......

            $write_result = socket_send($msgsock, $result, strlen($result), MSG_EOF);
            socket_close($msgsock);    
            //finished                    
        }            
    }
}

...
//create, bind, and listen $sock
...

while(($client = socket_accept($sock))){
    $clients[]=new Client($client); 
} 

?>

1 个答案:

答案 0 :(得分:1)

替换

while(($client = socket_accept($sock))){
    $clients[]=new Client($client); 
} 

使用

while ( $client = socket_accept($sock) )
{
    $clients[] = new Client($client);

    /* Loop through Array Clients and clean done ones to free some memory */
    foreach ($clients as $key=>$value) 
    {
        if ( (isset($clients[$key]['done'])) && ($clients[$key]['done']) )
        {
            socket_close($clients[$key]['socket']);
            unset($clients[$key]);
        }
    }
}

确保在析构函数中将$ this-&gt; done添加到您的客户端类以允许检测已完成的工作程序。

class Client extends Thread 
{  
    public $this->done;

    public function __construct($socket)
    {
        $this->socket = $socket;
        $this->done = false;
        $this->start();
    }

    public function __destruct($socket)
    {
        $this->done = true;
    }

    public function run()
    {
        // Your CODE Here!
    }
}