- 論壇徽章:
- 0
|
本帖最后由 heidern 于 2011-07-17 22:28 編輯
最近在研究多線程,想寫個(gè)服務(wù)器端程序.- #!/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();
- }
復(fù)制代碼 當(dāng)threadMonitor這個(gè)線程sleep的時(shí)候,主線程也會(huì)sleep,為什么?
另:我的測(cè)試方法是,先運(yùn)行這個(gè)腳本,然后開另外一個(gè)終端執(zhí)行下面的命令:
while(true);do echo "hello" |nc localhost 12340;done
剛開始執(zhí)行的時(shí)候還不錯(cuò),但server端執(zhí)行到sleep那的時(shí)候客戶端就會(huì)出現(xiàn)被阻塞的情況,5秒后就繼續(xù)了 |
|