Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Can I/O operations on the same IO::Socket be executed in different threads?

by Anonymous Monk
on May 14, 2015 at 00:56 UTC ( [id://1126621]=note: print w/replies, xml ) Need Help??


in reply to Can I/O operations on the same IO::Socket be executed in different threads?

#!/usr/bin/perl -- use strict; use warnings; use threads stack_size => 4096; use IO::Socket::INET; use Time::HiRes qw/ usleep /; use Data::Dump qw/ dd /; Main( @ARGV ); exit( 0 ); sub Main { my $host = "localhost:" . int( rand 99999 ); Dodo( $host, 'IO::Socket::INET' ); ## "works" ## Dodo( $host, 'IO::Socket::SSL' ); use IO::Socket::SSL; ## "doesn +'t" } ## end sub Main sub Dodo { my( $host, $socktype ) = @_; async( \&Server, $host, $socktype ); sleep 1; my $socket = $socktype->new( Proto => "tcp", PeerHost => $host, ) or die "Cannot start client : $!\n $@\n "; $socket->blocking( 0 ); async( \&Reader, $socket ); async( \&Writer, $socket ); $_->join for threads->list; } ## end sub Dodo sub Server { my( $host, $socktype ) = @_; my $tid = threads->tid; use Time::HiRes qw/ usleep /; my $server = $socktype->new( Proto => "tcp", LocalHost => $host, Listen => 1, Reuse => 1, ) or die "Cannot start tcp server: $!\n $@\n "; dd "listening on $host\n"; sleep 1; my $client = $server->accept(); while( <$client> ) { dd "echo reader($tid) $_"; print $client "echo reader($tid) $_"; last if /exit/i; } ## end while( <$client> ) } ## end sub Server sub Writer { my( $socket ) = @_; my $tid = threads->tid; for( 1 .. 20 ) { usleep 2000 * rand( 500 ); # 2000 sleep for 2 millisecond $socket->print( "writer($tid) " . scalar( gmtime ) . "\n" ); } ## end for( 1 .. 20 ) $socket->shutdown( 1 ); ## done writing } ## end sub Writer sub Reader { my( $socket ) = @_; my $tid = threads->tid; my $read = 0; while( $read < 1000 ) { my $readed = $socket->sysread( my $line, 51 ); next if !$readed; $read += $readed; dd "holymolyreaded($read/$readed) $line"; usleep 2000 * rand( 500 ); } ## end while( $read < 1000 ) $socket->print( "reader($tid) " . scalar( gmtime ) . " exit\n" ); } ## end sub Reader __END__
  • Comment on Re: Can I/O operations on the same IO::Socket be executed in different threads?
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1126621]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2024-04-26 06:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found