【问题标题】:pthreads how to destroy finished socket connectionspthreads如何销毁完成的套接字连接
【发布时间】:2017-03-18 18:40:31
【问题描述】:

我有如下代码,使用 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); 
} 

?>

【问题讨论】:

    标签: php multithreading sockets pthreads


    【解决方案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->done 添加为 true,以允许检测完成的工作线程。

    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!
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多