Modified my code in previous reply, now both server and clients reside in a single process. This makes the threading structure a little bit more complex. Don’t think this should replace the previous version of code, because of the architecture difference, so just create this new reply.
Also added yield() to all threads.
Code is tested.
use strict;
use IO::Socket;
use threads;
use threads::shared;
my $numClients = shift;
my $all_created : shared = 0;
$| = 1;
threads->create(\&server);
print "Creating $numClients clients...\n";
for (1..$numClients) {
my $socket = IO::Socket::INET->new(Proto => "tcp", PeerAddr => "lo
+calhost", PeerPort => 7001) || print "Socket creation error: $!\n";
threads->new(\&client, $socket, $_)->detach;
print ".";
}
print "\nAll Created\n";
sleep 1;
$all_created = 1;
<STDIN>;
sub server {
my $server = new IO::Socket::INET(Proto => "tcp", LocalPort => 700
+1, Listen => 5)
|| die "failed to establish socket\n";
while (1) {
my $client = $server->accept;
threads->create(\&client_handle, $client);
threads->yield;
}
}
sub client_handle {
my $client = shift;
while (<$client>) {
chomp;
print $client $_ + 1, "\n";
threads->yield;
}
}
sub client {
my ($socket,$id) = @_;
sleep 1 while (!$all_created);
print $socket "1\n";
while (<$socket>) {
chomp;
print "$id <<== $_\n";
print $socket $_ + 1, "\n";
threads->yield;
sleep 5;
}
return;
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.