You could try this:

#! perl -slw use strict; use threads; my @t = map async( sub { my $tid = threads->tid; my $worktime = shift; print "Thread $tid started with a worktime of $worktime"; eval { local $SIG{ ALRM } = sub { die 'times up' }; alarm 10; ## simulate doing work here sleep $worktime; print "Thread $tid: all done"; }; print "Thread $tid ended ", $@ ? " with error: $@" : 'normally'; }, 2*$_ + $ARGV[ 0 ] ), 1 .. 4; $_->join for @t; __END__ C:\test>junk78 5 Thread 1 started with a worktime of 7 Thread 2 started with a worktime of 9 Thread 3 started with a worktime of 11 Thread 4 started with a worktime of 13 Thread 1: all done Thread 1 ended normally Thread 2: all done Thread 2 ended normally Thread 4 ended with error: times up at C:\test\junk78.pl line 10. Thread 3 ended with error: times up at C:\test\junk78.pl line 10.

Whether this works -- ie. will interrupt what you are doing when the alarm goes off is subject to the same limitations as with normal perl.

Due to Deferred (safe) signals introduced in 5.7.x, there are some things it won't interrupt until the opcode completes or times out. But that's a 'Perl-thing' rather than a 'threads-thing'.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

The start of some sanity?


In reply to Re: Threads Timeout by BrowserUk
in thread Threads Timeout by Gary Yang

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.