After Perl 5.8.0 came out, more and more people started to use thread for various applications. I noticed that, lots of times, people use Perl thread for socket applications. That makes sense, as one thing thread does perfectly for you, is to avoid blocking.
One mistake that people make from time to time, in the threading area, is that they started to think thread is free. This includes myself. If you look at some of those examples I posted, you will see that I started to create demos which has one thread per connection on the server side.
As demos, they are probably fine, but for real applications, this is extremely harmful, and makes absolutely no sense. Thread is expensive, and really expensive.
The principle should be: only to create a new thread, when you see it as the best way to resolve blocking. As for socket application, most of the time, you can simply resolve blocking issues by using IO::Select.
Will there be a performance issue, because using less thread? No, on a single processor computer, threading does not improve performance at all, and even on multi-processor computer, threading only improves performance when you have the right number of threads. Keep in mind, at the most, there will only be one active thread really running, on any given processor, at any given time.
Recently there is
this interesting thread. For last couple of days, I have been thinking about the reason, that one can only have a little bit more than 100 socket (I will soon demo to you, that the limitation is actually not about socket, but about the number of thread one can have.)
Now let’s end this post with two piece of testing code. The first piece shows how quick you will reach the maximum number of thread you can have, due to the huge cost of each thread. The second one shows you that, the limitation is really not on the socket side (of course there is a limitation for number of sockets you can have, both because limited number of valid port, and the cost of each socket, but the per socket cost is much smaller than the cost per thread.)
#!/usr/bin/perl
use threads;
use strict;
my $count;
while (1) {
threads->create(\&func);
print ++$count, "\n";
}
sub func {
while (1) {
sleep(10);
}
}
Second piece:
#!/usr/bin/perl
use IO::Socket::INET;
use IO::Select;
use threads;
use Data::Dumper;
threads->create(\&server);
my $count;
while (1) {
my $c1 = new IO::Socket::INET(Proto => "tcp", PeerAddr => "127.1",
+ PeerPort => 3000) || die "Finished";
print "client socket ", ++$count, " uses local port ", $c1->sockpo
+rt(), "\n";
}
sub server {
my $s = new IO::Socket::INET(Proto => "tcp", LocalAddr => "127.1",
+ LocalPort => 3000, Listen => 1);
while (1) {
$s->accept();
}
}