use strict;
use warnings;
use IO::Socket::INET;
my $sock = IO::Socket::INET->async_new(
PeerAddr => 'board.perl-community.de',
PeerPort => 80,
Proto => "tcp",
Timeout => 1,
Type => SOCK_STREAM,
AsyncTimeout => 1000
);
package IO::Socket;
use strict;
use warnings;
use threads;
use threads::shared;
my $can_connect = 0;
my $is_shared = 0;
sub async_new_cb {
my ($self, $sockref, %args) = @_;
${$sockref} = $self->new(%args);
$can_connect = 1;
cond_signal($can_connect);
}
sub async_new {
my ($self, %args) = @_;
$args{AsyncTimeout} ||= 1000;
my $sockobj = undef;
my $thread = threads->create('async_new_cb', $self, \$sockobj, %args);
unless($is_shared) {
share($can_connect);
$is_shared = 1;
}
$can_connect = 0;
lock($can_connect);
until($can_connect) {
last if !cond_timedwait($can_connect, time() + $args{AsyncTimeout});
}
return $can_connect ? $sockobj : undef;
}
1;