Created
June 9, 2013 17:49
-
-
Save dex4er/5744499 to your computer and use it in GitHub Desktop.
Perl server fork vs threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use IO::Socket; | |
sub process_connection { | |
my ($sock, $addr) = @_; | |
while (my $line = <$sock>) { | |
$line =~ s/\015?\012$//; | |
if ($line =~ /^$/) { | |
print $sock "HTTP/1.0 200 OK\015\012Content-Type: text/plain\015\012\015\012Hello, world!\015\012"; | |
last; | |
}; | |
}; | |
} | |
my $server = IO::Socket::INET->new( LocalPort => 5000, Type => SOCK_STREAM, Reuse => 1, Listen => SOMAXCONN ) or die ("bind: $!\n"); | |
warn $server; | |
sub worker { | |
my ($n, $server) = @_; | |
while(my $client = $server->accept) { | |
#warn "$n: $client"; | |
my $addr = $client->peerhost; | |
process_connection($client, $addr); | |
} | |
} | |
my @childs; | |
for my $n (1..20) { | |
if (my $pid = fork) { | |
push @childs, $pid; | |
} | |
else { | |
worker($n, $server); | |
exit 0; | |
} | |
} | |
foreach my $pid (@childs) { | |
waitpid($pid, 0); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use threads; | |
use IO::Socket; | |
sub process_connection { | |
my ($sock, $addr) = @_; | |
while (my $line = <$sock>) { | |
$line =~ s/\015?\012$//; | |
if ($line =~ /^$/) { | |
print $sock "HTTP/1.0 200 OK\015\012Content-Type: text/plain\015\012\015\012Hello, world!\015\012"; | |
last; | |
}; | |
}; | |
} | |
my $server = IO::Socket::INET->new( LocalPort => 5000, Type => SOCK_STREAM, Reuse => 1, Listen => SOMAXCONN ) or die ("bind: $!\n"); | |
warn $server; | |
sub worker { | |
my ($n, $server) = @_; | |
while(my $client = $server->accept) { | |
#warn "$n: $client"; | |
my $addr = $client->peerhost; | |
process_connection($client, $addr); | |
} | |
} | |
for my $n (1..20) { | |
my $thr = threads->create(\&worker, $n, $server); | |
} | |
foreach my $thr (threads->list) { | |
$thr->join; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment