简体   繁体   English

Perl服务器中的内存泄漏

[英]Memory leak in perl server

I'm trying to write a multithreaded server with perl (Windows x64). 我正在尝试使用Perl(Windows x64)编写多线程服务器。 When trying to connect to it from another computer, I found the memory and handle usage kept going up, even if I maintained only one connection at a time. 尝试从另一台计算机连接到该计算机时,即使一次仅维护一个连接,我的内存和句柄使用率仍在上升。 And after thousands of trials it used up nearly all system memory. 经过数千次试验,它几乎耗尽了所有系统内存。 I can't figure out the reason. 我不知道原因。

Here is the server side: 这是服务器端:

use IO::Socket::INET;
use threads;

sub session_thread
{
    my $client_socket=$_[0];

    my $client_address = $client_socket->peerhost();
    my $client_port = $client_socket->peerport();
    print "connection from $client_address:$client_port\n";

    my $data = "";
    $client_socket->recv($data, 1024);
    print "$client_address:$client_port says: $data";

    $data = "ok";
    $client_socket->send($data);

    shutdown($client_socket, 1);
    $client_socket->close();
    threads->exit();
}

$| = 1;

my $socket = new IO::Socket::INET (
    LocalHost => '0.0.0.0',
    LocalPort => '7777',
    Proto => 'tcp',
    Listen => 5,
    ReuseAddr => 1
);
die "cannot create socket $!\n" unless $socket;
print "server waiting for client connection on port 7777\n";

while(1)
{
    my $client_socket = $socket->accept();
    threads->create('session_thread',$client_socket);
}

$socket->close();

Thanks. 谢谢。

You either have to wait for the thread to finish by joining it or tell Perl that you don't care about the thread's return value and that Perl itself should clean up the data once the thread exits. 您要么必须等待线程通过加入线程来完成,要么告诉Perl您不在乎线程的返回值,并且一旦线程退出,Perl本身应该清除数据。 The latter seems to match your use case and is done by detaching . 后者似乎与您的用例匹配,并且通过分离来完成。

Also note that using exit is not necessary in your example. 另请注意,在您的示例中不必使用exit You can simply return from the thread's subroutine normally. 您可以简单地从线程的子例程正常返回。 exit is used for ending a thread from a deeper nesting level within the program. exit用于从程序的更深层嵌套级别结束线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM