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.
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.