我正在尝试使用perl编写多线程服务器(Windows x64)。当试图从另一台计算机连接到它时,我发现内存和句柄使用率一直在上升,即使我一次只维护一个连接。经过数千次试验后,它耗尽了几乎所有的系统内存。我无法弄清楚原因。
这是服务器端:
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();
感谢。
答案 0 :(得分:6)
您必须等待线程完成joining it或告诉Perl您不关心线程的返回值,并且Perl本身应该在线程退出后清理数据。后者似乎与您的用例相匹配,由detaching完成。
另请注意,在您的示例中使用exit
为not necessary。您可以直接从线程的子例程返回。 exit
用于从程序中更深的嵌套级别结束线程。