- 论坛徽章:
- 0
|
本帖最后由 heidern 于 2011-07-17 22:28 编辑
最近在研究多线程,想写个服务器端程序.- #!/usr/local/perl5.12/bin/perl
- use strict;
- use warnings;
- use threads (
- 'exit' => 'threads_only',
- );
- use IO::Socket;
- use Data::Dumper;
- $|=1;
- my $serverFD=IO::Socket::INET->new(
- LocalPort => 12340,
- Type => SOCK_STREAM,
- Listen => SOMAXCONN,
- Reuse => 1
- ) || die $!;
- # create a thread to monitor the threads
- threads->create(\&threadMonitor);
- # when a connect accepted , create a thread to process it
- while (1) {
- threads->create(\&talk,$serverFD->accept());
- }
- sub talk
- {
- my ($clientFD,$clientInfo)=@_;
- my ($clientport,$clientaddr) = unpack_sockaddr_in($clientInfo);
- my $clientip = inet_ntoa($clientaddr);
- my $tid = threads->self->tid();
- print "Client From => $clientip\:$clientport My number is $tid\n";
- while (<$clientFD>) {
- print "client $tid from $clientip say: $_";
- chomp($_);
- if ($_ =~ m/hello/i) {
- print $clientFD "tid=$tid,Hello Client from $clientip\n";
- } elsif ($_ =~ m/bye/i) {
- print $clientFD "tid=$tid,Bye Bye Client from $clientip\n";
- close $clientFD;
- last;
- }
- }
- threads->self->detach();
- }
- sub threadMonitor
- {
- print "Monitor Thread Created!!\n";
- while(1) {
- my @ths_r=threads->list(threads::running);
- my $threadNums_running=$#ths_r+1;
- my @ths_j=threads->list(threads::joinable);
- my $threadNums_joinable=$#ths_j+1;
- print "There are $threadNums_running threads running and $threadNums_joinable threads joinable\n";
- sleep(5);
- }
- threads->self->detach();
- }
复制代码 当threadMonitor这个线程sleep的时候,主线程也会sleep,为什么?
另:我的测试方法是,先运行这个脚本,然后开另外一个终端执行下面的命令:
while(true);do echo "hello" |nc localhost 12340;done
刚开始执行的时候还不错,但server端执行到sleep那的时候客户端就会出现被阻塞的情况,5秒后就继续了 |
|