Here's one way to do it:
use IO::Handle;
# do stuff
my $input_thread = threads->new( \&getInput ); # start the thread
+, wait for input
# do stuff if you feel like it
my $input = $input_thread->join || 'default input'; # wait for thread
+to return
sub getInput {
my $h = IO::Handle->new_from_fd( *STDIN, r );
$h->blocking( 0 ); # don't wait for input to return from read()
+s
my $time = time();
my $input = '';
while( 1 ){
$h->read( $input, 20, 0 ); # read 20 chars of info if it's av
+ailable
chomp $input;
last if $input; # return if we got input
last if time() - $time > 5; # return if 5 seconds have passed
}
}
I'll admit that this isn't the most threads-specific way to do it: it could also be implemented without threads. But it
will allow you to do other things while data is being gathered, so I think it should work for you. If IO::Handle uses alarm, and I don't think it does, this will fail on Windows anyway.
I have another idea that's slightly more thread-dependent, but I don't have time to think it through or test it. You could send a signal to the thread after five seconds, and then join() it. The thread would have a local $SIG{SOMETHING} to catch the signal you throw at it, and exit without finishing whatever it's doing. How to send a signal to a thread, though, is doubtless an OS-dependent thing. If it has a separate PID and you can find it, great. If not, you may need to send a harmless (or intentionally ignored) signal to the main process. And it may just be impossible. ;)
--
Love justice; desire mercy.